Use the. NET Excel component to export an Excel file,
/// <Summary>
/// Export Excel
/// </Summary>
/// <Param name = "Source"> data to be exported </param>
/// <Param name = "exportfullpath"> export the full path of an Excel file </param>
/// <Param name = "hasheadline"> if true, the header is generated. </param>
Private void exportexcel (datatable source, string exportfullpath, bool hasheadline)
{
# Region export using the. NET Excel component
Application objexcel = new application ();
If (objexcel = NULL)
{
Throw new exception ("error: You must install Microsoft Excel application! ");
}
// Create an Excel file (not saved, no file name)
Workbooks objworkbooks = objexcel. workbooks;
_ Workbook objworkbook = objworkbooks. Add (xlwbatemplate. xlwbatworksheet); // sheet1 is created by default.
// Get sheet1
Sheets objsheets = objworkbook. worksheets;
_ Worksheet objworksheet = (_ worksheet) objsheets. get_item (1 );
// Write the title
Int intdatabeginrow = 1;
If (hasheadline)
{
For (INT I = 0; I <source. Columns. Count; I ++)
{
Objworksheet. cells [1, I + 1] = source. Columns [I]. columnname. Trim ();
}
// Add 1 to the start row of the data
Intdatabeginrow ++;
}
// Write data. The Excel Index starts from 1.
For (Int J = 0; j <source. Rows. Count; j ++)
{
For (int K = 0; k <source. Columns. Count; k ++)
{
Objworksheet. cells [J + intdatabeginrow, k + 1] = source. Rows [J] [K]. tostring ();
}
}
Objworksheet. hyperlinks. Delete (); // remove the hyperchain
// Save the file (if you use objworkbook. saveas, it will be incompatible with excel2000 and excelxp)
Objworkbook. _ saveas (exportfullpath, missing. value, missing. value, missing. value, missing. value, missing. value, xlsaveasaccessmode. xlnochange, missing. value, missing. value, missing. value, missing. value );
// Close the file and release the resource
Objworkbook. Close (false, exportfullpath, false );
Objexcel = NULL;
# Endregion
}
Call exportexcel directly.