2009年11月26日 星期四

將資料匯出到Excel或Word

做法一:
先在專案的參考中加入Microsoft Excel 9.0 Object Library 或 Microsoft Word 9.0 Object Library COM元件(版本依安裝的Office版本而有所不同)

注意事項:
1.執行程式時要先將Office光碟片放到光碟機內,系統可能會自動安裝某些元件
2.若執行過程發生錯誤,Excel或Word會卡在記憶體內(用工作管理員查看),如果無法將之強制"結束",就必須重新開機。

Excel 程式部分:

Dim oE As New Excel.ApplicationClass
Dim oWB As Excel.Workbook
Dim oWS As Excel.Worksheet

'oE.Workbooks.Open(Server.MapPath("Book1.xls")) '使用開啟舊檔

oWB = oE.Workbooks.Add '開新檔案

oE.DisplayAlerts = False
oWS = CType(oWB.Worksheets.Item("Sheet1"), Excel.Worksheet) '取得Sheet1
oWS.Range("A1:D5").Value = "Test" '寫入資料到儲存格

oWS.SaveAs(Server.MapPath("Book2.xls")) '另存新檔

oWS = Nothing

oWB.Close()
oWB = Nothing

oE.Quit()
oE = Nothing

Word程式部分:

Dim oW As New Word.ApplicationClass
Dim oD As Word.Document

oD = oW.Documents.Open(Server.MapPath("Doc1.doc")) '開啟舊檔

oW.Selection.TypeText("測試文字測試文字測試文字測試文字測試文字") '寫入資料

oD.SaveAs(FileName:=Server.MapPath("test.doc")) '另存新檔

oD.Close()
oD = Nothing

oW.Quit()
oW = Nothing


做法二:
Response.ContentType = "application/vnd.ms-excel;charset=big5" ‘execl
Response.AppendHeader("content-disposition", "attachment; filename=aaa.xls")


Response.ContentType = "application/msword" ‘word
Response.AppendHeader("content-disposition", "attachment; filename=aaa.doc")


做法三:
Response.AppendHeader("Content-Disposition", "attachment;filename=DormitorySchedule.xls")
Response.ContentEncoding = System.Text.Encoding.GetEncoding("big5")
Response.ContentType = "application/ms-excel"

Dim oStringWriter As System.IO.StringWriter
oStringWriter = New IO.StringWriter

Dim oHtmlTextWriter As System.Web.UI.Html32TextWriter
oHtmlTextWriter = New Html32TextWriter(oStringWriter)

DataGrid2.RenderControl(oHtmlTextWriter)
Response.Write(oStringWriter.ToString())
Response.End()


Response.AppendHeader("Content-Disposition", "attachment;filename=SpendItem.xls")
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8")
Response.ContentType = "application/ms-excel"

Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
Me.dgmaster.RenderControl(oHtmlTextWriter)

Response.Write(oStringWriter.ToString())
Response.End()


e.Item.Cells(2).Attributes.Add("style", "vnd.ms-excel.numberformat:@")

沒有留言:

張貼留言