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 ();
}
}
}
}