First, add an Excel reference. In the project, "add reference". Depending on the system environment, add Microsoft. office. interOP. some Excel files are added to the Microsoft Excel 11 Object Library (suitable for the office2003 environment), and Microsoft is referenced in it. office. core and excel.
The following is a useful function on the Internet:
# Region export data from the datagridview control to excel
/// <Summary>
/// Export data in the datagridview control to excel
/// </Summary>
/// <Param name = "gridview"> datagridview object </param>
/// <Param name = "isshowexcle"> whether to display the Excel page </param>
/// <Returns> </returns>
Public bool exportdatagridview (datagridview gridview, bool isshowexcle)
{
If (gridview. Rows. Count = 0)
Return false;
// Create an Excel Object
Excel. Application Excel = new excel. Application ();
Excel. application. workbooks. Add (true );
Excel. Visible = isshowexcle;
// Generate the field name
For (INT I = 0; I <gridview. columncount; I ++)
{
Excel. cells [1, I + 1] = gridview. Columns [I]. headertext;
}
// Fill in data
For (INT I = 0; I <gridview. RowCount-1; I ++)
{
For (Int J = 0; j <gridview. columncount; j ++)
{
If (gridview [J, I]. valuetype = typeof (string ))
{
Excel. cells [I + 2, J + 1] = "'" + gridview [J, I]. value. tostring ();
}
Else
{
Excel. cells [I + 2, J + 1] = gridview [J, I]. value. tostring ();
}
}
}
Return true;
} # Endregion
Add reference Microsoft Office Excel:
Using Excel = Microsoft. Office. InterOP. Excel;
Call:
If (! Rejected. exportdatagridview (dgvequiment, true ))
MessageBox. Show ("there is no data in the table and data cannot be exported! "," System prompt ", messageboxbuttons. OK, messageboxicon. information );
Very good, very powerful!