c#

通过C# Pandas如何导出数据到Excel或CSV文件

小樊
85
2024-07-12 00:27:30
栏目: 编程语言

在C#中使用Pandas库导出数据到Excel或CSV文件的方法如下:

  1. 导出数据到Excel文件:
using Python.Runtime;
using NumSharp;
using Pandas;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 创建一个DataFrame
        var data = new { Name = new[] { "Alice", "Bob", "Charlie" }, Age = new[] { 25, 30, 35 } };
        var df = new DataFrame(data);

        // 导出数据到Excel文件
        string excelFilePath = "data.xlsx";
        using (Py.GIL())
        {
            df.to_excel(excelFilePath);
        }

        Console.WriteLine($"数据已成功导出到Excel文件: {excelFilePath}");
    }
}
  1. 导出数据到CSV文件:
using Python.Runtime;
using NumSharp;
using Pandas;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 创建一个DataFrame
        var data = new { Name = new[] { "Alice", "Bob", "Charlie" }, Age = new[] { 25, 30, 35 } };
        var df = new DataFrame(data);

        // 导出数据到CSV文件
        string csvFilePath = "data.csv";
        using (Py.GIL())
        {
            df.to_csv(csvFilePath);
        }

        Console.WriteLine($"数据已成功导出到CSV文件: {csvFilePath}");
    }
}

以上代码示例演示了如何使用C#中的Pandas库将数据导出到Excel或CSV文件。首先创建一个DataFrame对象,然后使用to_excel()方法将数据导出到Excel文件,或使用to_csv()方法将数据导出到CSV文件。在使用Pandas库时,需要使用Python.Runtime库来进行交互。

0
看了该问题的人还看了