【问题标题】:C#: how to output matrices to tables in csv or Excel (with text headings)C#:如何将矩阵输出到 csv 或 Excel 中的表格(带有文本标题)
【发布时间】:2015-06-09 13:17:50
【问题描述】:

我有一些(最多 200 个)一维数值数组,都是双精度数,由我的程序创建。我需要将它们输出到 CSV 或 Excel 文件。具体来说,我需要创建一个表,其中每个数组是一列,标题是文本描述。 数组描述了某些项目的属性。所有项目都具有相同的属性。

这些数组是我用 Python 编写的数值模拟脚本的结果,现在正尝试转换为 C#,因为 Python 太慢了。

在 Python 中,我使用 pandas 数据框来存储所有这些列及其标题。我怎么能在 C# 中做到这一点?我可以使用像http://www.extremeoptimization.com/http://bluemountaincapital.github.io/Deedle/ 这样的库来创建类似于数据框的东西吗?商业的、非免费的图书馆很好。

在 Python 中,我创建了一个类,它定义了我正在建模的每个项目。假设我正在为 10 辆汽车建模,我将创建 10 个 Car 类的实例;每个类都将包含一个字符串,其中包含要在最终输出的标题中使用的描述、一维数组的定义以及一个使用所有数组创建数据框的方法。然后我为每辆汽车循环这个方法来创建最终的输出表,这样他的标题就会是这样的:

  • “项目 1 的详细描述 - 属性 A”
  • “项目 1 的详细描述 - 属性 B”
  • ...
  • “项目 2 的详细描述 - 属性 B”

等等

欢迎任何提示。非常感谢!

【问题讨论】:

    标签: c# arrays dataframe deedle


    【解决方案1】:

    部分是我的解决方案,不够好,但有效:

    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);
                }
            }
        }
    }
    

    使用:

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

    在你的情况下 - 试试 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()); 
            }
        }
    }
    

    【讨论】:

    • 非常感谢,我会试试的(我现在无法访问 C#)。您认为使用 DataTable 会更好/更快吗?我通常需要写入大约 50-60 MB 的数据(即 100 个 0.5 MB 的表,当导出为 CSV 时 - xlsx 文件会更小)。
    • 有了 DataTable,它将非常接近(速度上)数组(没有装箱/拆箱),无论如何link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2013-01-18
    • 2010-11-10
    • 1970-01-01
    相关资源
    最近更新 更多