string saveFileName = @"e:\xx.xls";
List<ExcelInfo>list=daochuInfo.selExcel();//資料來源
if (list.Count==0)
return;
bool fileSaved=false;
Excel.Application xlApp=new Excel.Application();
if(xlApp==null)
{
this.Page.RegisterStartupScript("script", "<script>alert('無法建立Excel對象,可能您的機子未安裝Excel');</script>");
return;
}
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
//寫入欄位
worksheet.Cells[1,1]="B";
worksheet.Cells[1, 2] = "C";
worksheet.Cells[1, 3] = "D";
//寫入數值
for(int r=0;r<list.Count;r++)
{
ExcelInfo excelInfo = (ExcelInfo)list[r];
worksheet.Cells[r+2,1]=excelInfo.B;
worksheet.Cells[r + 2, 2] = excelInfo.C;
worksheet.Cells[r + 2,3] = excelInfo.D;
}
worksheet.Columns.EntireColumn.AutoFit();//列寬自適應。
if(saveFileName!="")
{
try
{
workbook.Saved =true;
workbook.SaveCopyAs(saveFileName);
fileSaved=true;
}
catch(Exception ex)
{
fileSaved=false;
this.Page.RegisterStartupScript("script", "<script>alert('匯出檔案時出錯,檔案可能正被開啟!');</script>");
}
}
else
{
fileSaved=false;
}
xlApp.Quit();
GC.Collect();//強行銷毀
}
public static List<ExcelInfo> selExcel()
{
string str = "select b,c,d from tb_excel";
using (SqlConnection sqlCon = new SqlConnection(Database.conStr))
{
using (SqlCommand sqlCmd = new SqlCommand(str, sqlCon))
{
sqlCon.Open();
List<ExcelInfo> list = new List<ExcelInfo>();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
ExcelInfo excelInfo = new ExcelInfo();
excelInfo.B = dr[0].ToString();
excelInfo.C = dr[1].ToString();
excelInfo.D = dr[2].ToString();
list.Add(excelInfo);
}
return list;
}
}
}
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/ak_ljd/archive/2009/04/28/4134687.aspx