1. 程式人生 > >Net用DataTable導出Excel通用函數

Net用DataTable導出Excel通用函數

export message exit center exception inb this ram com

分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!http://www.captainbed.net

1,首先要導入Com文件Microsoft Excel 11.0 Object Library.
2,要添加Interop.Excel.dll文件
http://files.cnblogs.com/ghostljj/Interop.Excel.rar
3.執行下面步驟
/// <summary>
/// 導出Excel
/// </summary>
/// <param name="dt">要導出的DataTable</param>

public void ExportToExcel(System.Data.DataTable dt)
{
if (dt == null) return;
Excel.Application xlApp = new Excel.Application();
if (xlApp == null)
{
// lblMsg.Text = "無法創建Excel對象,可能您的機子未安裝Excel";
lblMsg.Text = GetLocalResourceObject("noexcel").ToString();
return;
}
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Excel.Range range = null;
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;

//寫入標題
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = (Excel.Range)worksheet.Cells[1, i + 1];
//range.Interior.ColorIndex = 15;//背景顏色
range.Font.Bold = true;//粗體
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//居中
//加邊框
range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);
//range.ColumnWidth = 4.63;//設置列寬
//range.EntireColumn.AutoFit();//自動調整列寬
//r1.EntireRow.AutoFit();//自動調整行高

}
//寫入內容
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i];
range = (Excel.Range)worksheet.Cells[r + 2, i + 1];
range.Font.Size = 9;//字體大小
//加邊框
range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);
range.EntireColumn.AutoFit();//自動調整列寬
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
}

range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
if (dt.Columns.Count > 1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
}

try
{
workbook.Saved = true;
workbook.SaveCopyAs(System.Web.HttpRuntime.AppDomainAppPath + "XMLFiles//EduceWordFiles//" + this.Context.User.Identity.Name + ".xls");
}
catch (Exception ex)
{
//lblMsg.Text = "導出文件時出錯,文件可能正被打開!/n" + ex.Message;
lblMsg.Text = GetLocalResourceObject("error").ToString() + "/n" + ex.Message;
}


workbooks.Close();
if (xlApp != null)
{
xlApp.Workbooks.Close();

xlApp.Quit();

int generation = System.GC.GetGeneration(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

xlApp = null;
System.GC.Collect(generation);
}
GC.Collect();//強行銷毀

#region 強行殺死最近打開的Excel進程
System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
System.DateTime startTime = new DateTime();
int m, killId = 0;
for (m = 0; m < excelProc.Length; m++)
{
if (startTime < excelProc[m].StartTime)
{
startTime = excelProc[m].StartTime;
killId = m;
}
}
if (excelProc[killId].HasExited == false)
{
excelProc[killId].Kill();
}
#endregion


//提供下載
BIClass.BusinessLogic.Util.ResponseFile(Page.Request, Page.Response, "ReportToExcel.xls"
, System.Web.HttpRuntime.AppDomainAppPath + "XMLFiles//EduceWordFiles//" + this.Context.User.Identity.Name + ".xls", 1024000);
}


//--------------------------------------------------------
4.如果是放在IIS中,現在是不能到出的,還要配置一下
方案一:在Web.config中添加
<system.web>
<identity impersonate="true" userName="管理員名" password="密碼" />
<system.web>
方案二:
(1)在運行->dcomcnfg打開組件服務
(2) 在 控制臺根目錄->組件服務->計算機->我的電腦->DCOM配置->Microsoft Excel應用程序->屬性->安全
(3)啟動和激活權限->使用自定義->添加一個ASPNET用戶,還有打開本地啟動本地激活
訪問權限->使用自定義->添加一個ASPNET用戶,還有打開本地訪問遠程訪問

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!http://www.captainbed.net

Net用DataTable導出Excel通用函數