我编写了一个代码来从 Excel 文件中读取一列。我在此使用 Microsoft.Office.Interop.Excel,首先读取整个 Range,然后写入 System.Array,然后对 System.Array 值进行一些操作,最后将其转换为 List,因为我填充了 ListBox 元素。这是代码(仅相关部分):
private List<string> bd = new List<string>();
private static System.Array objRowAValues;
private List<string> bl = new List<string>();
private static System.Array objRowBValues;
private List<string> cm = new List<string>();
private static System.Array objRowCValues;
private List<string> pl = new List<string>();
private List<string> bdCleanList;
private static Microsoft.Office.Interop.Excel.Application appExcel;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range rngARowLast, rngBRowLast, rngCRowLast;
long lastACell, lastBCell, lastCCell, fullRow;
private void btnCargarExcel_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (System.IO.File.Exists(openFileDialog1.FileName))
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
filePath.Text = openFileDialog1.FileName.ToString();
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false,
false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
fullRow = xlWorkSheet.Rows.Count;
lastACell = xlWorkSheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row;
rngARowLast = xlWorkSheet.get_Range("A1", "A" + lastACell);
objRowAValues = (System.Array)rngARowLast.Cells.Value;
foreach (object elem in objRowAValues)
{
if (elem != "")
{
bd.Add(cleanString(elem.ToString(), 10));
}
}
nrosProcesados.Text = bd.Count().ToString();
listBox1.DataSource = bd;
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
executiontime.Text =
String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10).ToString();
}
else
{
MessageBox.Show("No se pudo abrir el fichero!");
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
appExcel = null;
System.Windows.Forms.Application.Exit();
}
}
}
我用大约 800 000 个单元格的 Excel 文件进行测试,用时不到 2 分钟。然后我从 EPPlus 测试样本并且比我的方法更快,所以我认为使用 EPPlus 而不是 Microsoft.Office.Interop.Excel 我认为也在使用 OpenXML SDK(但找不到任何适合我目标的示例,所以我离开现在)。在示例中,他们使用此代码从 Excel 文件中读取:
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
var query1= (from cell in sheet.Cells["d:d"] where cell.Value is double && (double)cell.Value >= 9990 && (double)cell.Value <= 10000 select cell);
他们当然在这里使用 LINQ,但我关于这个主题的问题是:
- 您使用了哪种方法?
- 您对此有何建议?
- 使用 EPPlus 或 OpenXML SDK 编写相同的内容有什么帮助吗?
我是来自 PHP 世界的 C# 世界的新手,这是我的第一个项目