c# - c#数据表插入到具有大记录集的excel很慢4500条记录超过6分钟
问题描述
我将一组数据从 SQL 返回到数据表。数据表的原因是我在多个地方使用记录集。
当我使用数据表将数据插入到 Excel 中时,使用大约 4500 条记录的 for 循环非常慢,需要 6 分钟以上。我正在寻找一些关于调整我的代码以使其更快的指导。
我意识到你们中的很多人会讨厌我的评论,但我仍在学习,他们在我编写这个项目时会帮助我
void ExcelOutput()
{
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
//Get a new workbook. and set the sheets up
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Name = "Records";
for (int i = 0; i < 2; i++)
{
oWB.Sheets.Add(After: oWB.Sheets[oWB.Sheets.Count]);
}
oWB.Sheets[2].Activate();
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Name = "Matters";
oWB.Sheets[3].Activate();
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Name = "Notes";
//Code to add another sheet if required
oWB.Sheets.Add(After: oWB.Sheets[oWB.Sheets.Count]);
oWB.Sheets[4].Activate();
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Name = "Optional FN LN Only Search";
//Code to add another sheet if required
//oWB.Sheets.Add(After: oWB.Sheets[oWB.Sheets.Count]);
//reset back to required sheet
oWB.Sheets[3].Activate();
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "Data From";
oSheet.Cells[1, 2] = "Attatched to";
oSheet.Cells[1, 3] = "Key ID";
oSheet.Cells[1, 4] = "Subject";
oSheet.Cells[1, 5] = "Notes";
oSheet.Cells[1, 6] = "Contact Name";
x = 2;
y = 1;
foreach (DataRow dr in dtNotesConflict.Rows)
{
oSheet.Cells[x, 1] = dr["datafrom"];
oSheet.Cells[x, 2] = dr["Attach_to"];
oSheet.Cells[x, 3] = dr["Key_ID"];
oSheet.Cells[x, 4] = dr["subject"];
oSheet.Cells[x, 5] = dr["notes"];
oSheet.Cells[x, 6] = dr["Contact_Name"];
x = x + 1;
}
解决方案
我有一个解决方案。在 6 分钟内用 Excel 写入 4000 个寄存器。我得到了减少接下来的步骤:
创建二维数组
对象[,] arr = 新对象[list.Count, countColumnVisibles];
使用反射填充这个对象(在我的例子中)。
计算放置表格的范围。
范围 c1 = worksheet.Range["B3"]; c2 = worksheet.Cells["3" + list.Count - 1, countColumnVisibles + 1] 作为范围;range = worksheet.get_Range(c1, c2);
使用以下方法获取 Range 区域
get_value
:范围范围 = worksheet.get_Range(c1, c2);
设定值:
范围.值 = arr;
重要提示:3、4 和第 5 点之后使循环填充对象数组。并使用二维数组而不是列表。
推荐阅读
- c# - ConvertAPI : 将文档作为流上传以转换为 PDF 返回乱码数据
- django - 已解决:带有 SFTP 的 Django-Storages:GET 请求失败
- java - 盒子在另一个盒子下面移动,而不是在盒子里移动 - JavaFX
- python - Pyside PlainText 占位符文本未显示
- sql - SQL-根据列的特定值检索记录
- c# - 调用其他单元测试方法的方法的基于状态与交互的测试
- sql-server - 将弹性作业进程 ID 传递给目标数据库
- asynchronous - 两个相互冲突的长期流程管理器
- python - 带有 C++ 绑定的 VSCode Intellisense Python
- python - 如何修复错误:“tensorflow.compat.v2.__internal__”没有属性“register_call_context_function”