終於完成了從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();
}