How to Handle the Excel Empty Column Issue

When operating excel, there may be a lot of invalid data rows. The following is my simple processing method

 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                  // If there are 10 empty rows, skip 
28                  if (emptyBlockCount > 2 )
 29                      break ;
 30              }
 31  
32              objBook. Save();
 33              objBook.Close();
 34              excel.Quit();
 35  
36              return  true ;
 37          }
View Code

The violent decision is made by recording the number of blank lines.

If anyone has a better way, please let me know.

When Excel closes, there may be a problem that it cannot be closed in time. 

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

Through the Windows system function, the process is forcibly killed.

In the process of operating excel, it is best to open a separate thread to do these things. After my attempts, an excel with 200 valid cells takes more than 30 seconds to update.

If it is placed in the main thread, it is basically GG. Good luck to everyone.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325214119&siteId=291194637