我正在使用 MySQL 数据库中的值更新 Excel 工作簿中的值。WorkbookMap
列表中只有 11 行,DataTables
而RptValueSet
DataSet
. 我已经证明问题出在这个循环中,而不是与数据库的通信中。获得结果很快,但将它们写入工作簿很慢。当DataTables
inDataSet
很小时,下面的代码可以正常工作 - 例如 3 列 7 行结果集,并且我几乎立即收到更新的 Excel 工作簿。但是,当结果集增加时,循环会明显变慢;3 列 50 行DataTable
会导致返回更新的 Excel 工作簿时延迟 7 - 10 秒。我不确定我真的需要把DataTables
进入一个集合,但这是我能弄清楚如何迭代它们的唯一方法。任何有关优化此循环的提示将不胜感激!
// Create a list to contain the destination for the data in the workbook
List<WorkbookMap> wbMap = new List<WorkbookMap>();
// Create a new data set to contain results from database
DataSet RptValuesSet = new DataSet();
// RptValuesSet populated from database here....
// Create a collection so we can loop thru the dataset
DataTableCollection RptValuesColl = RptValuesSet.Tables;
for (int i = 0; i < RptValuesColl.Count; i++)
{
DataTable tbl = RptValuesColl[i];
// Find the correct entry in the workbook map
for (int j = 0; j < wbMap.Count; j++)
{
if (wbMap[j].SPCall == tbl.TableName)
{
// Write the results to the correct location in the workbook
MovingColumnRef = wbMap[j].StartColumn;
for (int c = 1; c < tbl.Columns.Count; c++)
{
row = wbMap[j].StartRow; // start at the top row for each new column
for (int r = 0; r < tbl.Rows.Count; r++)
{
// Write the database value to the workbook given the sheetName and cell address
UpdateValue(wbMap[j].SheetName, MovingColumnRef + row, tbl.Rows[r][c].ToString(), 0, wbMap[j].String);
row++;
}
MovingColumnRef = IncrementColRef(MovingColumnRef);
}
}
}
}