How to use c # To export DataTable data to Execl

Source: Internet
Author: User

Export DataTable data to Execl format
The source code is as follows:
First, a new dialog box is saved:
 

Private System. Windows. Forms. SaveFileDialog m_objSave = new SaveFileDialog ();
// Data export Method
Public void m_mthExportToExecl ()
{
This. m_objSave.DefaultExt = "xls ";
This. m_objSave.Filter = "Excel file (*. xls) | *. xls ";

If (this. m_objSave.ShowDialog () = DialogResult. OK)
{
M_mthDoExport (dtFindCharge, m_objSave.FileName );
}

}
// Specific export Method
Private void m_mthDoExport (DataTable dtSource, string strFileName)
{
Int rowNum = dtSource. Rows. Count;
Int columnNum = dtSource. Columns. Count;
Int rowIndex = 1;
Int columnIndex = 0;

If (dtSource = null | string. IsNullOrEmpty (strFileName ))
{
Return;
}
If (rowNum> 0)
{
Excel. Application xlApp = new Excel. ApplicationClass ();
XlApp. DefaultFilePath = "";
XlApp. DisplayAlerts = true;
XlApp. SheetsInNewWorkbook = 1;
Excel. Workbook xlBook = xlApp. Workbooks. Add (true );
// Import the column name of DataTable into the first row of the Excel table
Foreach (DataColumn dc in dtSource. Columns)
{
ColumnIndex ++;
XlApp. Cells [rowIndex, columnIndex] = dc. ColumnName;
}
// Import data in DataTable to Excel
For (int I = 0; I <rowNum; I ++)
{
RowIndex ++;
ColumnIndex = 0;
For (int j = 0; j <columnNum; j ++)
{
ColumnIndex ++;
XlApp. Cells [rowIndex, columnIndex] = dtSource. Rows [I] [j]. ToString ();
}
}
XlBook. SaveCopyAs (strFileName );
XlApp = null;
XlBook = null;
}
}

Related Article

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.