Add the reference assembly Microsoft. Office. Interop. Excel
Declare using Excel = Microsoft. Office. Interop. Excel;
And the POST method:
// Export the data of the DataGridView Excel File
Private void ExportExcel (string fileName, DataGridView myDGV)
{
String saveFileName = "";
// Bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog ();
SaveDialog. DefaultExt = "xls ";
SaveDialog. Filter = "Excel file | *. xls ";
SaveDialog. FileName = fileName;
SaveDialog. ShowDialog ();
SaveFileName = saveDialog. FileName;
If (saveFileName. IndexOf (":") <0)
Return; // canceled
Microsoft. Office. Interop. Excel. Application xlApp = new Microsoft. Office. Interop. Excel. Application ();
If (xlApp = null)
{
MessageBox. Show ("an Excel object cannot be created, maybe your computer has not installed Excel ");
Return;
}
Microsoft. Office. Interop. Excel. Workbooks workbooks = xlApp. Workbooks;
Microsoft. Office. Interop. Excel. Workbook workbook = workbooks. Add (Microsoft. Office. Interop. Excel. XlWBATemplate. xlWBATWorksheet );
Microsoft. Office. Interop. Excel. Worksheet worksheet = (Microsoft. Office. Interop. Excel. Worksheet) workbook. Worksheets [1]; // get sheet1
String [] array = new string [myDGV. Columns. Count];
// Obtain columns with Visble = true
Foreach (DataGridViewColumn column in myDGV. Columns)
{
If (column. Visible = true)
{
Array [column. DisplayIndex] = column. HeaderText + '|' + column. Name ;;
}
}
Int RowsCount = myDGV. Rows. Count;
Int ColumnsCount = array. Length;
Int mm = 1;
For (int I = 0; I <ColumnsCount; I ++)
{
String [] str = new string [2];
String ColumnName;
Try
{
Str = array. GetValue (I). ToString (). Split ('| ');
ColumnName = str [0];
}
Catch
{
Continue;
}
// Export the column name www.2cto.com
Worksheet. Cells [1, mm] = ColumnName;
// Export the column content
For (int m = 0; m <RowsCount; m ++)
{
Try
{
Worksheet. Cells [m + 2, mm] = myDGV. Rows [m]. Cells [str [1]. FormattedValue. ToString ();
}
Catch
{}
}
// Execute a column of mm ++
Mm ++;
}
Worksheet. Columns. EntireColumn. AutoFit ();
If (saveFileName! = "")
{
Try
{
Workbook. Saved = true;
Workbook. SaveCopyAs (saveFileName );
}
Catch (Exception ex)
{
MessageBox. Show ("An error occurred while exporting the file. The file may be opened! \ N "+ ex. Message );
}
}
XlApp. Quit ();
GC. Collect (); // forcibly destroy
MessageBox. Show (the table information of fileName + "is saved successfully.", "prompt", MessageBoxButtons. OK );
}
From Qiu zhengxiang's column