c#大量二维数组数据导出到excel,先选择文件地址,再将文件保存到指定地址,使用多个线程来分块写入数据,从而提高生成速度,代码示例
时间: 2024-03-21 08:41:18 浏览: 14
以下是一个基于C#的多线程写入Excel的示例代码,可以将大量二维数组数据导出到Excel中:
```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelExporter
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please select the file path to save the Excel file:");
string savePath = Console.ReadLine();
// Create a new Excel workbook and worksheet
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
// Generate some sample data
int rowCount = 10000; // Total row count
int chunkSize = 100; // Rows to write per thread
int threadCount = rowCount / chunkSize;
int[][] data = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
{
data[i] = new int[] { i, i * 2, i * 3 };
}
// Write data to Excel using multiple threads
Parallel.For(0, threadCount, i =>
{
int startRow = i * chunkSize + 1; // Excel row index starts from 1
int endRow = Math.Min((i + 1) * chunkSize, rowCount);
for (int j = startRow; j <= endRow; j++)
{
for (int k = 0; k < data[j - 1].Length; k++)
{
worksheet.Cells[j, k + 1] = data[j - 1][k];
}
}
});
// Save Excel file
workbook.SaveAs(savePath);
workbook.Close();
excel.Quit();
Console.WriteLine("Excel file saved!");
}
}
}
```
这个示例程序会要求用户输入Excel文件保存路径,然后使用多个线程并行写入数据到Excel文件中,最终保存并关闭Excel文件。可以根据具体情况修改代码中的数据生成方式、行数、线程数和写入方式等参数。