c# - 将数据表复制到 Excel

标签 c# datatable

我有一个大小为 m x n 的数据表,我想将所有内容(包括列标题)复制到一个已打开的 excel 文件中。我有对 Excel.WorkBook 的引用,并且知道数据将复制到哪个 WorkSheet。

我知道最简单(也是最脏)的方法是:

Excel.WorkSheet outSheet; //set to desired worksheet
int rowIdx = 1;
int colIdx = 1;
//add header row
foreach (DataColumn dc in dt.Columns)
{
    outSheet.Cells[rowIdx, colIdx++] = dc.ColumnName;
}

colIdx = 1; //reset to Cell 1

//add rest of rows
foreach (DataRow dr in dt.Rows)
{
    colIdx = 0;
    foreach (DataColumn dc in dt.Columns)
    {
        outSheet.Cells[rowIdx + 1, colIdx + 1] = dr[colIdx].ToString();
        colIdx++;
    }
    rowIdx++;
}

这可行,但不幸的是会产生大量时间成本,因为它需要逐个单元地访问和粘贴数据。有没有更好的方法来实现这一点?

最佳答案

我为你写了一个小例子。 tl;dr 您可以将一组值分配 到 Excel 范围。但是这个必须满足一些规范。学分转到Eric Carter

    Stopwatch sw = new Stopwatch();
    sw.Start();
    Application xlApp = new Application();
    Workbook xlBook = xlApp.Workbooks.Open(@"E:\Temp\StackOverflow\COM_Interop_CS\bin\Debug\demo.xlsx");
    Worksheet wrkSheet = xlBook.Worksheets[1];            

    try
    {
        /// credits go to: 
        /// http://blogs.msdn.com/b/eric_carter/archive/2004/05/04/126190.aspx
        /// 
        /// [cite] when you want to set a range of values to an array, you must declare that array as a 2 
        /// dimensional array where the left-most dimension is the number of rows you are going to set and 
        /// the right-most dimension is the number of columns you are going to set.  
        /// 
        /// Even if you are just setting one column, you can’t create a 1 dimensional array and have it work[/cite]

        Excel.Range range = wrkSheet.Range["A1", "Z100000"];
        int maxRows = 100000, maxCols = 26;
        object[,] values = new object[maxRows, maxCols];

        int counter = 0;
        for (int row = 0; row < maxRows; row++)
        {
            for (int col = 0; col < maxCols; col++)
            {
                values[row, col] = counter++;
            }
        }
        range.Value2 = values;                
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
    xlApp.Visible = true;
    sw.Stop();
    Console.WriteLine("Elapsed: {0}", sw.Elapsed);

我在不到 10 秒的时间内添加了 100.000 行和 26 列。我希望这适合您!

关于c# - 将数据表复制到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25512628/

相关文章:

r - 如何使用其他列 (R) 中的值创建列?

c# - 将 "friendly"列名添加到 LINQ to SQL 模型的好方法是什么?

c# - IIS URL 重写模块 : Get ApplicationPath

javascript - 如何使用 C# 和 Angular js 在 View 上显示数据

c# - 无法从 DataGridView 获取值到另一个表单

c# - 指定的转换在 linq 查询中无效

c# - 当绑定(bind)属性声明为接口(interface)类型与类类型时,WPF 绑定(bind)行为不同?

c# - 如何增加 WinForms 中 ListViewItems 的 AutoPopDelay 值?

jquery - DataTables,获取隐藏单元格的值

c# - LinQ 查询从 DataTable 中选择 DataRow