[C#] 使用ClosedXML导出excel(且设置其带有时间戳的导出名字)

前段时间项目里有个关于报表变更, 将导出的报表名要带有yyyyMMdd这种的时间戳. 整理了一个简单关于ClosedXML的小demo:

1. 首先要在项目中引入两个library:ClosedXML.dllDocumentFormat.OpenXml.dll
2. 在项目代码中加入引用:usingClosedXML.Excel;
3. demo方法(在代码的最后部分使用了Response来设置export出excel的名字,当时修改这段代码时候出现了上下文不存在Response的错误,解决办法请参照:解决办法:The name 'Response' does not exist in the current context 本文代码已经解决该异常):

/// <summary>
/// Export an Excel using ClosedXML
/// http://blog.csdn.net/dietime1943
/// </summary>
/// <returns>Returns a byte array object.</returns>
public byte[] FunctionDownload()
{
    string[] ReportColumn = { "A", "B" };                   // A,B column
    string[] ReportColumn_values = { "NAME", "ADDRESS" };   // VALUE
    string nowTimeStamp = GetTimeStamp();
    string basePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
    string path = basePath + Common.Constants.Template.LocalPath;
    string sourceFile = path + "Export2ExcelForm.xlsx";
    string destinationFile = path + "ReportForm" + nowTimeStamp + ".xlsx";
    File.Copy(sourceFile, destinationFile, false);

    using (XLWorkbook wb = new XLWorkbook(destinationFile))
    {
        var ws = wb.Worksheet(1);
        int row = 1; // + result.IndexOf(resultone);
        for (int m = 0; m < ReportColumn.Count(); m++)
        {
            ws.Cell(row, ReportColumn[m]).Value = ReportColumn_values[m]; // A,F column
        }
        
        //using (var ms = new MemoryStream())
        //{
        // wb.SaveAs(ms);
        // File.Delete(destinationFile);
        // return ms.ToArray();
        //}
        
        // 设置report保存的时候名称为: ReportName_yyyyMMdd.xlsx
        using (var ms = new MemoryStream())
        {
            wb.SaveAs(ms);
            //return ms.ToArray();
            
            string printdate = Calendar.GetCurrentDate().ToString("yyyyMMdd");
            string myName = "ReportForm" + "_" + printdate + ".xlsx";
            
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + myName);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            // HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.End();
            File.Delete(destinationFile);
            return ms.ToArray();
        }
    }
}

本文原创由`bluetata`发布于blog.csdn.net、转载请务必注明出处。

Flag Counter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bluetata

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值