asp.net中将DataGrid中的数据导入到excel中,并设置其格式

来源:互联网 发布:合同矩阵 编辑:程序博客网 时间:2024/05/03 01:39

         终于完成了从datagrid 中导入excel,为了防止忘记,特意记录下来,为大家和自己提供方便。

web应用程序中主要代码如下:

//设置DataGrid2数据源 ,并绑定(由于这一步很简单,所以略过)

/*设置DataGrid2的格式为文本型,这样就解决了导入excel之后,形如“00000123”变成了“123”的问题。在这里,为了简单起见,我设置了dataGrid总的属性。也可以为每个单元格设置属性,如DataGrid2.Items[0].Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@");*/
DataGrid2.Attributes.Add(
"style","vnd.ms-excel.numberformat:@");

//将DataGrid2中的数据以刘的形式写入excel文件中
Response.Clear(); 
Response.Buffer
= true
Response.Charset
="GB2312";
Response.AppendHeader(
"Content-Disposition","attachment;filename=zjxx.xls"); 
Response.ContentEncoding
=System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
this.EnableViewState = false;    
System.Globalization.CultureInfo myCItrad 
= new System.Globalization.CultureInfo("ZH-CN",true);
System.IO.StringWriter oStringWriter 
= new System.IO.StringWriter(myCItrad); 
System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);
this.DataGrid2.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();

 

 

windows应用程序中如下:

 

//其中zjtable中已经从数据库中读入了数据
Excel.ApplicationClass excelApp ;
excelApp 
= new Excel.ApplicationClass();
Excel.Workbook excelBook 
=excelApp.Workbooks.Add(1);
Excel.Worksheet excelSheet
=(Excel.Worksheet)excelBook.Worksheets[1];

excelApp.Visible
=true;
excelSheet.Cells[
1,1]="姓名";
excelSheet.Cells[
1,2]="性别";
excelSheet.Cells[
1,3]="出生日期";

//设置excel文件中所有的单元格为文本型
excelSheet.Cells.NumberFormatLocal="@";
for(int i=0;i < zjtable.Rows.Count  ;i++)
{
//将zjtable中的数据导入到excel文件中
    DataRow row=zjtable.Rows[i];
    
for (int j=1;j<=3;j++)
                          excelSheet.Cells[i
+2,j]=row[j].ToString();
}