How to export data in the datagridview to excel

Source: Internet
Author: User
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Windows. forms;
Using system. IO;

Namespace outputtoexecl
{
Public class exportxls
{
Public exportxls ()
{

}
Public static void exportdatagridviewtoexcel (datagridview datagridatagridatagri1)
{
Savefiledialog = new savefiledialog ();
Savefiledialog. Filter = "execl files (*. xls) | *. xls ";
Savefiledialog. filterindex = 0;
Savefiledialog. restoredirectory = true;
Savefiledialog. createprompt = true;
Savefiledialog. Title = "Export an Excel file ";

Savefiledialog. showdialog ();

Stream mystream;
Mystream = savefiledialog. openfile ();
Streamwriter Sw = new streamwriter (mystream, system. Text. encoding. getencoding ("gb2312 "));
String STR = "";
Try
{
// Write the title
For (INT I = 0; I <datagridview1.columncount; I ++)
{
If (I> 0)
{
STR + = "\ t ";
}
STR + = maid [I]. headertext;
}

Sw. writeline (STR );
// Write content
For (Int J = 0; j <datagridview1.rows. Count; j ++)
{
String tempstr = "";
For (int K = 0; k <datagridview1.columns. Count; k ++)
{
If (k> 0)
{
Tempstr + = "\ t ";
}
Tempstr + = maid [J]. cells [K]. value. tostring ();
}
Sw. writeline (tempstr );
}
Sw. Close ();
Mystream. Close ();
}
Catch (exception E)
{
MessageBox. Show (E. tostring ());
}
Finally
{
Sw. Close ();
Mystream. Close ();
}
}

}
}

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.