c#当我将db数据导出到excel文件时,文件名被破坏

时间:2017-12-07 04:37:28

标签: c# excel character-encoding export-to-excel

当我尝试将DB数据导出到excel文件时,

英文文件名没问题,但是当我尝试设置文件名韩文

文件名已损坏。

但是当我打开导出的excel文件时,它打开得很好,所有文本都没问题。

如何修复保存文件名代码?

我的代码如下。

btnSaveClick事件

  protected void btnMemSaveExcel_Click(object sender, EventArgs e)
    {
        //set Excel header as string[] ExcelHeaders

        try
        {
            //Get siteTitle to use Excel file name.
            string siteTitle = SPContext.Current.Site.OpenWeb().Title;

            //some codes..
            ExcelExport(Page.Response, ds.Tables[0], siteTitle + "_MemberList", siteTitle + "_MemberList", ExcelHeader, true)
        }
    }

Excel导出

private static void ExcelExport(HttpResponse response, DataTable dataTable, string fileName, string sheetTitle, string[] colHeader, bool borderLine)
{
    ExcelWorkSheet ws = null;
    int rowNum = 1;

    if(dataTable != null && dataTable.Rows.Count > 0)
    {
        ExcelPackage pck = new ExcelPackage();
        ws = pck.WorkBook.Worksheets.Add(sheetTitle);

        //set header, set data, etc

        response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xlsx", fileName));

        response.BinaryWrite(pck.GetAsByteArray());
        response.End();
    }
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

添加新行

string fileSaveName = HttpUtility.UrlPathEncode("fileName.TrimEnd());

修改代码

response.AddHeader("content-dispositon", string.Format("attachment; filename={0}.xlsx", fileSaveName));