asp.net中將DataGrid中的資料匯入到excel中,並設定其格式

來源:互聯網
上載者:User

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.