excel使用OpenXml丢失数据/变得腐败

时间:2015-04-09 10:02:12

标签: c# excel openxml

我正在尝试在excel中保存一些内容。保存后,我提供下载选项。 我的代码是:

  private void OpenWorkSheet(string workbookName, FormCollection frm)
        {

            using (var document = SpreadsheetDocument.Open(workbookName,true))
            {
                var workbookPart = document.WorkbookPart;
                var workbook = workbookPart.Workbook;
                var sheet = workbookPart.Workbook.Descendants<Sheet>().ToList();
                Worksheet worksheet1 = ((WorksheetPart)(workbookPart.GetPartById(sheet[0].Id))).Worksheet;

                if (sheet == null)
                    throw new Exception("No sheet found in the template file. Please add the sheet");

                //insertion in sheet1
                ExcelOxml.SetCellValue(document, worksheet1, 3, 6, Convert.ToString(frm["ACName"]), false);
                ExcelOxml.SetCellValue(document, worksheet1, 3, 8, Convert.ToString(frm["AcNum"]), false);


                bool setv = ExcelOxml.SetSpreadsheetCellValue(worksheet1, "F", 6, Convert.ToString(frm["name"]));
                setv = ExcelOxml.SetSpreadsheetCellValue(worksheet1, "F", 8, Convert.ToString(frm["newvexpansion"]));
                setv = ExcelOxml.SetSpreadsheetCellValue(worksheet1, "F", 10, Convert.ToString(frm["userdefinedsegment"]));

                worksheet1.Save();


                document.Close();

        // Download logic   
                string XlsPath = Server.MapPath(@"~/ExcelTemplate/GCG Pricing.xlsm");
                FileInfo fileDet = new System.IO.FileInfo(XlsPath);
                Response.Clear();
                Response.Charset = "UTF-8";
                Response.ContentEncoding = Encoding.UTF8;
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileDet.Name));
                Response.AddHeader("Content-Length", fileDet.Length.ToString());
                Response.ContentType = "application/ms-excel";
                Response.WriteFile(fileDet.FullName);
                Response.End();

            }
        }

保存数据后,我可以选择在本地机器中保存文件后打开/保存文件。并打开它会给出错误:

Excel在GCG + Pricing.xlsm&#39;中找到了不可读的内容。您想要深入了解此工作簿的内容吗?如果您信任此工作簿的来源,请单击是。

我的文件名是GCG Pricing.xlsm但是下载后它变为GCG + Pricing.xlsm。

感谢任何帮助。 感谢。

0 个答案:

没有答案