日期:2014-05-18  浏览次数:20484 次

导出数据到execl如何设置sheet的名称
我用下面这个函数来把数据导出到execl
public   void   CreateExcel(DataSet   ds)
{

HttpResponse   resp;

resp   =   Page.Response;

resp.ContentEncoding   =   System.Text.Encoding.GetEncoding( "GB2312 ");

resp.ContentType   =   "application/ms-excel ";

resp.AppendHeader( "Content-Disposition ",   "attachment;filename= "   +   DateTime.Now.ToString( "yyyyMMddHHmmss ")   +   ".xls ");

string   colHeaders   =   " ",   ls_item   =   " ";

int   i   =   0;

//定义表对象与行对像,同时用DataSet对其值进行初始化  

DataTable   dt   =   ds.Tables[0];

DataRow[]   myRow   =   dt.Select( " ");

//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符  

for   (i   =   0;   i   <   ds.Tables[0].Columns.Count;   i++)

colHeaders   +=   dt.Columns[i].Caption.ToString()   +   "\t ";

colHeaders   +=   "\n ";

//向HTTP输出流中写入取得的数据信息  

resp.Write(colHeaders);

//逐行处理数据      

foreach   (DataRow   row   in   myRow)
{

//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n  

for   (i   =   0;   i   <   ds.Tables[0].Columns.Count;   i++)

ls_item   +=   row[i].ToString()   +   "\t ";

ls_item   +=   "\n ";

//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据          

resp.Write(ls_item);

ls_item   =   " ";

}

resp.End();

}
导出后的电子表格的sheet的名称与文件名一样,但是我想统一设置成Sheet1,请高手指点一下!多谢了!

------解决方案--------------------
Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks oBooks;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Sheets oSheets;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oCells;
string sFile = Server.MapPath( "\\MyExcel.xls ");
oExcel.Visible = false;
oExcel.DisplayAlerts = false ;
oBooks = oExcel.Workbooks;
oBooks.Add(Type.Missing);
oBook=oExcel.ActiveWorkbook;
oSheets = oBook.Worksheets;
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets[1];
oSheet.Name = "Second Sheet ";
oCells = oSheet.Cells;  
oCells[2,5] = "测试数据A ";
oCells[2,6] = "测试数据B ";
//这里要根据你机器上office的版本调整参数个数,自己看一下saveas方法需要几个参数,适当添加或删除,我现在用的2007,10参数。
oSheet.SaveAs(sFile ,Type.Missing,Type.Missing,Type.Missing,Type.Missing ,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
oBook.Close(null,null,null);
oExcel.Quit();
Marshal.ReleaseComObject(oCells);
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oSheets);
Marshal.ReleaseComObject(oBook) ;
Marshal.ReleaseComObject(oBooks) ;
Marshal.ReleaseComObject(oExcel);
oExcel = null ;
oBooks = null ;
oBook = null;
oSheets = null ;
oSheet = null ;
oCells = null;
System.GC.Collect();
Response.Write( " <script> alert( '生成Excel成功