导出数据到 Excel 表格的相关问题

星辰hq 星辰hq 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
例子:有一个Excel模板(模板.xlsx),复制,生成一个新的表格(Report.xlsx),再从数据库导出数据到这个新的表格(Report.xlsx)
问题:不知道如何复制生成新的表格,然后再插入数据???

前台.cs文件

<asp:Button runat="server" ID="SheetBtn" OnClick="SheetBtn_Click" Text="生成Excel" />

后台事件

protected void SheetBtn_Click(object sender, EventArgs e)
{
StringBuilder strSQL = new StringBuilder();
strSQL.Clear();
strSQL.Append("select * from Report");
string strsql = strSQL.ToString();
DataTable dt = DB.GetDataBySQL(strsql);

DataTableToXml.DataTableToExcel(dt, "D:/vs2012/MainPage4/Report/report.xlsx");

}

DataTableToXml类文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Microsoft.Office.Interop.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using System.IO;

/// <summary>
/// DataTableToXml 的摘要说明
/// </summary>
public class DataTableToXml
{

/// <summary>
/// dataTable存成excel表格
/// 备注:如果strFileName处已经存在文件,则报错
/// </summary>
/// <param name="dtSource">dataTable</param>
/// <param name="strFileName">在服务端完整路径</param>
public static void DataTableToExcel(System.Data.DataTable dtSource, string strFileName, string sheetName)
{
int rowNum = dtSource.Rows.Count;
int columnNum = dtSource.Columns.Count;
int rowIndex = 1; //开始插入的行数
int columnIndex = 0; //起始行的第几个单元格插入内容

if (dtSource == null || string.IsNullOrEmpty(strFileName))
{
return;
}
if (rowNum > 0)
{
#region
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 2;
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//将DataTable的列名导入Excel表第一行
foreach (DataColumn dc in dtSource.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//将DataTable中的数据导入Excel中
xlApp.Cells.NumberFormat = "@";//设置所有cells格式为字符串。设置类型要在个Cell赋值之前
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dtSource.Rows[i][j].ToString();
}
}
xlBook.SaveCopyAs(strFileName);
//结束Excel进程的代码
xlBook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);//关闭book
xlApp.Quit();//关闭excel
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);//释放COM组件
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlBook = null;//如果有Ragne,Sheet,WorkBooks等对象,也要null
xlApp = null;

GC.GetTotalMemory(false);//回收调用xlApp产生的垃圾
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
#endregion

}
}

}


得出的效果图:

Excel模板:

想要的效果:
...全文
评论 4
收藏 已收藏
分享
返回顶部
星辰hq
C# 111,129 成员 642,540 内容