[C#] 纯文本查看 复制代码
#region public static void ExportExcel(string, DataSet, string) 根据模板配置文件,导出装载好数据后的Excel文件。
/// <summary>
/// 根据模板配置文件,导出装载好数据后的Excel文件。
/// </summary>
/// <param name="p_XmlName">Xml配置文件名。</param>
/// <param name="p_DataSet">数据源对象。</param>
/// <param name="p_ExportName">导出的Excel文件名。</param>
public static void ExportExcel(string p_XmlName, DataSet p_DataSet, string p_ExportName)
{
int maxrowcount = 300;
double decexcelcount = 1;
foreach (DotNetTable dt in p_DataSet.Tables)
{
double maxcount = Math.Ceiling(dt.Rows.Count * 1.0 / maxrowcount);
if (maxcount > decexcelcount)
decexcelcount = maxcount;
}
if (decexcelcount > 1)
{
for (int i = 0; i < decexcelcount; i++)
{
foreach (DotNetTable dt in p_DataSet.Tables)
{
DataSet ds_new = new DataSet();
double maxcount = Math.Ceiling(dt.Rows.Count * 1.0 / maxrowcount);
if (maxcount == 1.0)
{
DotNetTable dt_new = dt.Clone();
ds_new.Tables.Add(dt_new);
}
else
{
DotNetTable dt_new = new DotNetTable(dt.TableName);
dt_new = dt.Clone();
dt_new.Rows.Clear();
int remainrowscount = dt.Rows.Count - i * maxrowcount;
if (remainrowscount > maxrowcount)
remainrowscount = maxrowcount;
for (int j = 0; j < remainrowscount; j++)
{
DataRow dr_new = dt.Rows[i * maxrowcount + j];
dt_new.Rows.Add(dr_new.ItemArray);
}
ds_new.Tables.Add(dt_new);
}
}
ExportExcel(p_XmlName, p_DataSet, p_ExportName + "_" + (i + 1).ToString(), "");
}
}
else
{
ExportExcel(p_XmlName, p_DataSet, p_ExportName, "");
}
}
#endregion
2.用模版导出excel
#region public static void ExportExcel(string, DataSet, string) 根据模板配置文件,导出装载好数据后的Excel文件。
/// <summary>
/// 根据模板配置文件,导出装载好数据后的Excel文件。
/// </summary>
/// <param name="p_XmlName">Xml配置文件名。</param>
/// <param name="p_DataSet">数据源对象。</param>
/// <param name="p_ExportName">导出的Excel文件名。</param>
public static void ExportExcel(string p_XmlName, DataSet p_DataSet, string p_ExportName, string strmore)
{
KillExcel();
_Application xApplication = null;
string sBookPathT = null;
try {
//初始化Excel模板对象
string sRootPath1 = string.Format(@"{0}\", HttpContext.Current.Server.MapPath("~/") + TFLConstants.Cfg_XmlTempURL);
string sRootPath2 = string.Format(@"{0}\", HttpContext.Current.Server.MapPath("~/") + TFLConstants.Cfg_TempFileFolderName);
if (!Directory.Exists(sRootPath2)) {
Directory.CreateDirectory(sRootPath2);
}
//删除该目录下超过180天的临时文件
try {
DirectoryInfo dirInfo = new DirectoryInfo(sRootPath2);
foreach (FileInfo tFile in dirInfo.GetFiles()) {
if ((DateTime.Now.Date - tFile.CreationTime).TotalDays > 180) {
tFile.Delete();
}
}
} catch {
}
string sXmlPath = string.Format("{0}{1}.xml", sRootPath1, p_XmlName);//Xml配置文件全路径
ExcelSchema schema = GetExcelSchema(sXmlPath);
string sBookPathS = string.Format("{0}{1}.xls", sRootPath1, schema.XlsFile);//模板文件全路径
sBookPathT = string.Format("{0}{1}{2}.xls", sRootPath2, DateTime.Now.ToString("yyyyMMddHHmmss"), schema.XlsFile);
//Excel应用程序初始化
xApplication = new ApplicationClass();
xApplication.Visible = true;
xApplication.DisplayAlerts = false;
//装载模板文件,另存为新的文件
Workbook xWorkBook = xApplication.Workbooks.Add(sBookPathS);
xWorkBook.SaveAs(sBookPathT, _MValue, _MValue, _MValue, _MValue, _MValue, XlSaveAsAccessMode.xlNoChange, _MValue, _MValue, _MValue, _MValue, _MValue);
//创建原始数据Sheet
foreach (DotNetTable dt in p_DataSet.Tables) {
foreach (WSheet sheet in schema.WSheets) {
if (sheet.TableName == dt.TableName && dt.Rows.Count > 0) {
//填充数据
Worksheet xWorkSheet = xWorkBook.Worksheets[string.IsNullOrEmpty(sheet.SheetName) ? sheet.TableName : sheet.SheetName] as Worksheet;
int iRowCount = dt.Rows.Count;
int iColumnCount = dt.Columns.Count;
object[,] objs = new object[iRowCount, iColumnCount];
for (int i = 0; i < iRowCount; i++) {
for (int j = 0; j < iColumnCount; j++) {
objs[i, j] = dt.Rows[j];
}
}
xWorkSheet.get_Range(xWorkSheet.Cells[1, 1], xWorkSheet.Cells[iRowCount, iColumnCount]).Value2 = objs;
break;
}
}
}
//运行宏
if (!string.IsNullOrEmpty(schema.MacroName)) {
xApplication.Run(schema.MacroName, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue,
_MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue,
_MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue);
}
//删除宏模块
List<string> ModuleList;
if (string.IsNullOrEmpty(schema.ModuleNames)) {
ModuleList = new List<string>();
} else {
ModuleList = new List<string>(schema.ModuleNames.Split(new char[] { ',' }));
}
foreach (VBComponent macro in xWorkBook.VBProject.VBComponents) {
if (macro.Type == vbext_ComponentType.vbext_ct_StdModule || macro.Type == vbext_ComponentType.vbext_ct_ClassModule) {
if (!ModuleList.Contains(macro.Name)) {
xWorkBook.VBProject.VBComponents.Remove(macro);
}
}
}
//保存改变,销毁资源
xWorkBook.Save();
try {
xWorkBook.Close(null, null, null);
xApplication.Workbooks.Close();
xApplication.Quit();
} catch {
KillExcel(xApplication);
}
//Marshal.ReleaseComObject(xWorkBook);
//Marshal.ReleaseComObject(xApplication);
//xApplication = null;
//GC.Collect();
//导出Excel文件,并删除临时文件
p_ExportName = string.Format("{0}.xls", string.IsNullOrEmpty(p_ExportName) ? schema.XlsFile : p_ExportName);
ResponseHelp.ResponseFile(p_ExportName, En_ResponseType.Excel, sBookPathT);
} finally {
try {
if (File.Exists(sBookPathT)) {
File.Delete(sBookPathT);
}
} catch { }
KillExcel(xApplication);
}
}
#endregion
3.导出excel
#region private static void ResponseToClient(string, En_ResponseType, string, bool) 将服务器端文件以流的方式响应给客户端。
/// <summary>
/// 将服务器端文件以流的方式响应给客户端。
/// </summary>
/// <param name="aFileName">提供给客户端的默认文件名。</param>
/// <param name="aResponseType">输出流的HTTP-MIME类型。</param>
/// <param name="aContent">服务器上文件的全路径或内容。</param>
/// <param name="bIsFile">服务器端信息是文件还是内容的方式。</param>
private static void ResponseToClient(string aFileName, En_ResponseType aResponseType, string aContent, bool bIsFile) {
HttpResponse resp = HttpContext.Current.Response;
resp.Clear();
resp.Buffer = true;
switch(aResponseType) {
case En_ResponseType.Excel:
resp.ContentType = "application/vnd.ms-excel";
aFileName = aFileName.ToLower().EndsWith(".xls") ? HttpUtility.UrlEncode(aFileName) : HttpUtility.UrlEncode(aFileName + ".xls");
break;
case En_ResponseType.Txt:
resp.ContentType = "application/vnd.ms-txt";
aFileName = aFileName.ToLower().EndsWith(".txt") ? HttpUtility.UrlEncode(aFileName) : HttpUtility.UrlEncode(aFileName + ".txt");
break;
}
resp.AppendHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", aFileName));
if(bIsFile) {
resp.WriteFile(aContent);
} else {
resp.Write(aContent);
}
resp.Flush();
resp.Close();
}
#endregion