C # export data in the datagridview to excel

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.