C#: how to output matrices to tables in csv or Excel (with text headings)

474 views Asked by At

I have some (up to 200) one-dimensional numerical arrays, all doubles, created by my program. I need to output them to a CSV or to an Excel file. Specifically, I need to create a table, where each array is a column, and the headings are text descriptions. The arrays describe the attributes of certain items. All items have the same attributes.

The arrays are the result of a numerical simulation script which I had coded in Python and am now trying to convert to C# because Python is too slow.

In Python I use a pandas dataframe to store all these columns and their headings. How could I do it in C#? Could I use a library like http://www.extremeoptimization.com/ or http://bluemountaincapital.github.io/Deedle/ to create something similar to a dataframe? Commercial, not-free libraries are fine.

In Python I created a class which defines each of the item I am modelling. Say I am modelling 10 cars, I would create 10 instances of the class Car; each class would contain a string with the description to be used in the headings of the final output, the definition of the one-dimensional arrays, and a method which creates a dataframe with all the arrays. I then loop through this method for each of the cars to create the final output table, so that the he headings will be something like:

  • "long description of Item 1 - attribute A"
  • "long description of Item 1 - attribute B"
  • ...
  • "long description of Item 2 - attribute B"

etc.

Any tip would be most welcome. Thanks a lot!

1

There are 1 answers

2
Sadovyj Michael On

partially my solution, not good enough, but works :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace X
{
    class CreateExcelDoc
    {
        private Microsoft.Office.Interop.Excel.Application app = null;
        private Microsoft.Office.Interop.Excel.Workbook workbook = null;
        private Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
        private Microsoft.Office.Interop.Excel.Range workSheet_range = null;

        public void DisposeAll()
        {
            app = null;
            workbook = null;
            worksheet = null;
            workSheet_range = null;

            GC.Collect();
        }

        public void CreateExcelDoc()
        {
            try
            {
                app = new Microsoft.Office.Interop.Excel.Application();
                app.Visible = true;
                workbook = app.Workbooks.Add(1);
                worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];

                SetSheetStyle();
            }
            catch (Exception e)
            {
                MessageBox.Show("Error : " + e.Message);
            }
            finally
            {
            }
        }

        private void SetSheetStyle()
        {
            worksheet.Range["A1", "Z1000"].Style.Font.Name = "Arial";
            worksheet.Range["A1", "Z1000"].Style.Font.Size = 10;
            worksheet.Range["A1", "J1000"].Style.Font.Bold = true;
        }

        public void AddHeaders()
        {
            addData(1, 1, "A");
            addData(1, 2, "B");
            addData(1, 3, "C");
        }

        public void AddCell(int row, int col, object data)
        {
            if (data == null)
                return;

            try
            {
                if (data is string && (string)data != "EOF")
                    worksheet.Cells[row, col] = (string)data;
                else if (data is double)
                    worksheet.Cells[row, col] = (double)data;
                else if (data is long)
                    worksheet.Cells[row, col] = (long)data;
                else if (data is decimal)
                    worksheet.Cells[row, col] = (decimal)data;
                else throw new Exception("type unsupported");
            }
            catch(Exception e)
            {
                MessageBox.Show("write error(unsupported" format ?)\n" + e.Message);
            }
        }

        public void addData(int row, int col, string data,
            string cell1, string cell2, string format)
        {
            worksheet.Cells[row, col] = data;
            workSheet_range = worksheet.get_Range(cell1, cell2);
            workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
            workSheet_range.NumberFormat = format;
        }

        public void addData(int row, int col, string data)
        {
            try
            {
                string cell = ((char)(64 + col)).ToString() + row.ToString();

                int n;
                bool isNumeric = int.TryParse("123", out n);
                string format = (isNumeric == true) ? "#,##0" : "";

                addData(row, col, data, cell, cell, format);
            }
            catch (Exception e)
            {
                Form1.BallonInfo(e.Message);
            }
        }
    }
}

using :

CreateExcelDoc saveExcel = new CreateExcelDoc();
saveExcel.AddHeaders();
...
int i = 2;
foreach (var item in dataArray)
{
    saveExcel.AddCell(i, 1, item);
    i++;
}   
...
saveExcel.DisposeAll();

in your case - try csv :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace temp
{
    class Program
    {
        static void Main(string[] args)
        {
            // init
            string filePath = @"C:\myFile.csv";  
            string delimiter = ";";  

            // filling data
            double[] dataArray = new double[100];
            for (int i = 0; i < dataArray.Length; i++)
            {
                dataArray[i] = i;
            }

            // positioning data
            string[][] output = new string[101][];
            output[0] = new string[] { "Header 1", "Header 2", "Header 3" };
            for (int i = 0; i < dataArray.Length ; i++)
            {
                output[i+1] = new string[] { dataArray[i].ToString()};
            }

            // creating csv in stringBuilder
            StringBuilder sb = new StringBuilder();
            for (int index = 0; index < output.Length; index++)
            {
                sb.AppendLine(string.Join(delimiter, output[index]));
            }

            // save in file
            File.WriteAllText(filePath, sb.ToString()); 
        }
    }
}