.Net用DataTable导出Excel通用函数(修正了Excel进程删除不掉问题)

1.首先要导入Com文件Microsoft Excel 11.0 Object Library.
2.要添加Interop.Excel.dll文件
http://files.cnblogs.com/ghostljj/Interop.Excel.rar
3.执行下面步骤

[code lang=”csharp”]
///
/// 导出Excel
///
///要导出的DataTable
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);
}

//——————————————————–
[/code]

4.如果是放在IIS中,现在是不能到出的,还要配置一下
方案一:在Web.config中添加

方案二:
(1)在运行->dcomcnfg打开组件服务
(2) 在 控制台根目录->组件服务->计算机->我的电脑->DCOM配置->Microsoft Excel应用程序->属性->安全
(3)启动和激活权限->使用自定义->添加一个ASPNET用户,还有打开本地启动和本地激活
访问权限->使用自定义->添加一个ASPNET用户,还有打开本地访问和远程访问

本博客所有文章如无特别注明均为原创

如果觉得对你有帮助,可以通过下方打赏对作者表示鼓励

本文采用知识共享署名-非商业性使用-相同方式共享

如若转载,请注明出处:《.Net用DataTable导出Excel通用函数(修正了Excel进程删除不掉问题)》https://www.fangsi.net/26.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
锋哥的头像锋哥管理员
上一篇 2013年5月2日 17:30
下一篇 2013年5月3日 09:47

相关推荐

发表回复

登录后才能评论

评论列表(2条)