如何处理Excel空列问题

在操作excel的时候, 可能会出现很多的无效数据行. 下面是一个我的简单处理方式

 1         public static bool DataSetToExcel(DataSet dataSet, string fileName)
 2         {
 3             //建立Excel对象 
 4             var excel = new Microsoft.Office.Interop.Excel.Application();
 5             var objBook = excel.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
 6             excel.Visible = false;
 7             var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)objBook.Worksheets["data"];
 8             DataTable dataTable = DT(dataSet.Tables);
 9             int rowNumber = dataTable.Rows.Count;//不包括字段名 
10             int columnNumber = dataTable.Columns.Count;
11             int colIndex = 0;
12             int emptyBlockCount = 0;
13             //生成字段名称 
14             foreach (DataColumn col in dataTable.Columns)
15             {
16                 colIndex++;
17                 excel.Cells[1, colIndex] = col.ColumnName;
18             }
19             for (int r = 0; r < rowNumber; r++)
20             {
21                 for (int c = 0; c < columnNumber; c++)
22                 {
23                     worksheet.Cells[r + 2, c + 1] = dataTable.Rows[r][c];
24                 }
25                 if (string.IsNullOrWhiteSpace(dataTable.Rows[r][0].ToString()))
26                     emptyBlockCount++;
27                 // 如果有10个空行,跳过
28                 if (emptyBlockCount > 2)
29                     break;
30             }
31 
32             objBook.Save();
33             objBook.Close();
34             excel.Quit();
35 
36             return true;
37         }
View Code

暴力的通过记录空行数量,进行抉择.

如果哪位有更好的方法,请不吝赐教.

excel在关闭的时候,可能会出现不能及时关闭的问题. 

1         [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
2         static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
3 
4 
5             int lpdwProcessId;
6             GetWindowThreadProcessId(new IntPtr(excel.Hwnd), out lpdwProcessId);
7             System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
View Code

通过Windows的系统函数,强制杀掉进程.

在操作excel的过程中,最好单独开一个线程来做这些事情.经过我的尝试.一个拥有200个有效单元格的excel,就需要30秒以上的时间来更新.

如果放在主线程中,基本就GG了.祝大家好运.

猜你喜欢

转载自www.cnblogs.com/Fivee/p/8986659.html