0

在 Internet 上搜索并尝试了一些代码后,我使用 Interop 将数据从 Excel 导出到 Datatable。问题是,它非常慢。有人可以给我一个钥匙,我怎样才能用 Interop 更快地完成它,而不是 OLEDB 或其他任何东西?

我的代码:

object misValue = System.Reflection.Missing.Value;

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(userSelectedFilePath2);
Excel._Worksheet xlWorksheet1 = xlWorkbook.Sheets[1];
Excel.Range xlRange1 = xlWorksheet1.UsedRange;

DataTable excelTb1 = new DataTable();

for (int j = 1; j <= xlRange1.Columns.Count; j++) // Header Names
{
    excelTb1.Columns.Add(xlRange1.Cells[1, j].Value2.ToString());
}

DataRow dataRow = null;

for (int row = 2; row < xlRange1.Rows.Count + 1; row++)
{
    dataRow = excelTb1.NewRow();

    for (int col = 1; col <= xlRange1.Columns.Count; col++)
    {
        dataRow[col - 1] = (xlRange1.Cells[row, col] as Excel.Range).Value2;
    }
    excelTb1.Rows.Add(dataRow);
}

xlWorkbook.Close(true, misValue, misValue);
xlApp.Quit();
dataGridView1.DataSource = excelTb1;
4

2 回答 2

1

I'll give you an answer to a question you didn't ask. Use NPOI library.

  • it will be faster
  • you won't have problems with forgetting to close your resources
  • Excel will not be required or used in the background

Here's the relevant code for that: NPOI : How To Read File using NPOI . For xlsx formats, use XSSFWorkbook instead (it is available starting from version 2.0).

于 2012-11-12T13:24:14.430 回答
0

我对此的第一个想法是,您正在循环遍历 Excel 工作表并在数组中逐个转换值以填充您的结构。

尝试更多类似的东西(原谅我的 VB,但我相信 oyu 会理解我的建议):

Dim SpreadsheetVals(,) as object
SpreadhseetVals = xlWorksheet1.UsedRange

然后在你的数组中循环。

这应该会大大提高速度。

于 2012-11-12T14:21:07.200 回答