Intercepting part of the core code in a project example
—————————————————————————————— Core Code Section
This.toolStripProgressBar1.Maximum = this.datagridview1.rows.count-1;
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application ();
Microsoft.Office.Interop.Excel.Workbook ExcelWorkbook = Excel. APPLICATION.WORKBOOKS.ADD (TRUE);
Excel. Visible = false;//Whether Excel text is displayed
Try
{
Asynchronous execution to ensure no lag of foreground window program
Await Task.run (() =
{
for (int i = 0; i < This.dataGridView1.Columns.Count; i++)//Copy table column header
{
Excel. Cells[1, i + 1] = This.datagridview1.columns[i]. The row and column index of the Headertext;//excel object is starting from 1
The DataGridView index is starting from 0.
}
for (int i = 0; i < this.datagridview1.rows.count-1; i++)/minus one row of the column header
{
for (int j = 0; J < This.dataGridView1.Columns.Count; J + +)
{
if (This.datagridview1.rows[i + 1]. CELLS[J]. Value==null)
{
Excel. Cells[i + 2, j + 1] = "'";//when the table cell is empty, the row is persisted and skipped
Break
}
else if (this.datagridview1.rows[i + 1]. CELLS[J]. ValueType = = typeof (String))
{
Excel. Cells[i + 2, j + 1] = "'" + this.datagridview1.rows[i + 1]. CELLS[J]. Value.tostring ();
}
Else
{
Excel. Cells[i + 2, j + 1] = this.datagridview1.rows[i + 1]. CELLS[J]. Value.tostring ();
}
}
this.toolstripprogressbar1.value++;//Progress bar Forward
}
});
}
catch (Exception ex)
{
}
Finally
{
Save XLS Table
ExcelWorkbook. SaveAs ("111.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Freeing resources
if (excelworkbook!=null)
ExcelWorkbook. Close (Missing.Value, Missing.Value, Missing.Value);
if (Excel! = null)
{
Excel. Workbooks.close ();
Excel. Quit ();
}
—————————————————————— Follow-up code non-core code
It's mainly two points of attention.
①microsoft.office.interop.excel.application object The row and column index of Excel is starting from 1, and DataGridView is distinguished from the 0 start index,
② if the value of the Datagirdview cell is of type string, add a '
Microsoft.Office.Interop.Excel.dll components required for development Http://pan.baidu.com/s/1jGrPHrS
C # Prints the table on the DataGridView control to an Excel file