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