69b3850b
由於EXCEL 2003有65536行資料的限制,故在超過這個限制時須分成多個Sheet來顯示,本人通過網上部分資料加上自己的應用心得總結出以下方法,希望能為廣大工友帶來方便.
首先,如果您使用的是VS2005,則須引入Excel.dll檔案;如果您使用的是VS2003,則引入Interop.Excel.dll檔案,一般工程會自動引入.
然後,引用命名空間:using Excel;
最後添加方法:
/// <summary>
/// 將傳入的DataSet資料匯出至Excel檔案
/// </summary>
/// <param name="ctl">DataGrid</param>
public static void DataSet2Excel(DataSet ds)
{
int maxRow=ds.Tables[0].Rows.Count;
string fileName=DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//設定匯出檔案的名稱
DataView dv=new DataView(ds.Tables[0]);//將DataSet轉換成DataView
string fileURL=string.Empty;
//調用方法將檔案寫入伺服器,並擷取全部路徑
fileURL=DataView2ExcelBySheet(dv,fileName);
//擷取路徑後從伺服器下載檔案至本地
HttpContext curContext=System.Web.HttpContext.Current;
curContext.Response.ContentType="application/vnd.ms-excel";
curContext.Response.ContentEncoding=System.Text.Encoding.Default;
curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
curContext.Response.Charset = "";
curContext.Response.WriteFile(fileURL);
curContext.Response.Flush();
curContext.Response.End();
}
/// <summary>
/// 分Sheet匯出Excel檔案
/// </summary>
/// <param name="dv">需匯出的DataView</param>
/// <returns>匯出檔案的路徑</returns>
private static string DataView2ExcelBySheet(DataView dv,string fileName)
{
int sheetRows=65535;//設定Sheet的行數,此為最大上限,本來是65536,因表頭要佔去一行
int sheetCount = (dv.Table.Rows.Count - 1) / sheetRows + 1;//計算Sheet數
GC.Collect();//記憶體回收
Application excel;
_Workbook xBk;
_Worksheet xSt=null;
excel = new ApplicationClass();
xBk = excel.Workbooks.Add(true);
//定義迴圈中要使用的變數
int dvRowStart;
int dvRowEnd;
int rowIndex = 0;
int colIndex = 0;
//對全部Sheet進行操作
for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++)
{
//初始化Sheet中的變數
rowIndex = 1;
colIndex = 1;
//計算起始行
dvRowStart = sheetIndex * sheetRows;
dvRowEnd = dvRowStart + sheetRows-1;
if (dvRowEnd > dv.Table.Rows.Count-1)
{
dvRowEnd = dv.Table.Rows.Count - 1;
}
//建立一個Sheet
if (null == xSt)
{
xSt = (_Worksheet)xBk.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
}
else
{
xSt = (_Worksheet)xBk.Worksheets.Add(Type.Missing, xSt, 1, Type.Missing);
}
//設定Sheet的名稱
xSt.Name = "Expdata";
if (sheetCount > 1)
{
xSt.Name += ((int)(sheetIndex + 1)).ToString();
}
//取得標題
foreach (DataColumn col in dv.Table.Columns)
{
//設定標題格式
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter; //設定標題置中對齊
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).Font.Bold = true;//設定標題為粗體
//填值,並進行下一列
excel.Cells[rowIndex, colIndex++] = col.ColumnName;
}
//取得表格中數量
int drvIndex;
for(drvIndex=dvRowStart;drvIndex<=dvRowEnd;drvIndex++)
{
DataRowView row=dv[drvIndex];
//新起一行,目前的儲存格移至行首
rowIndex++;
colIndex = 1;
foreach (DataColumn col in dv.Table.Columns)
{
if (col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
}
else if (col.DataType == System.Type.GetType("System.String"))
{
excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
}
else
{
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
colIndex++;
}
}
//使用最佳寬度
Range allDataWithTitleRange = xSt.get_Range(excel.Cells[1, 1], excel.Cells[rowIndex, colIndex-1]);
allDataWithTitleRange.Select();
allDataWithTitleRange.Columns.AutoFit();
allDataWithTitleRange.Borders.LineStyle = 1;//將匯出Excel加上邊框
}
//設定匯出檔案在伺服器上的檔案夾
string exportDir="~/ExcelFile/";//注意:該檔案夾您須事先在伺服器上建好才行
//設定檔案在伺服器上的路徑
string absFileName = HttpContext.Current.Server.MapPath(System.IO.Path.Combine(exportDir,fileName));
xBk.SaveCopyAs(absFileName);
xBk.Close(false, null, null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
//返回寫入伺服器Excel檔案的路徑
return absFileName;
}
說明:如果您需要將匯出檔案儲存到伺服器,則只需採用DataView2ExcelBySheet方法即可,且不需返迴路徑,直接在伺服器的該路徑下即可找到檔案.