【问题标题】:Creating CSV file generates corrupted data创建 CSV 文件会生成损坏的数据
【发布时间】:2018-10-19 03:20:06
【问题描述】:

我有 ff。创建 CSV 文件的代码。我为此使用了 SpreadsheetLight 库,如果通过 MS Excel 打开它,但通过文本编辑器打开它时效果很好,看起来文本被加密或损坏。我认为这是一个编码问题,但我不确定我的代码缺少什么或应该更正。

MemoryStream ms = new MemoryStream();
SLDocument slDoc = new SLDocument();

slDoc.RenameWorksheet(SLDocument.DefaultFirstSheetName, detailList.exam_module_value);
slDoc.SetCellValue(1, 1, "[Question#]");
slDoc.SetCellValue(1, 2, "[Question]");
slDoc.SetCellValue(1, 3, "[Letter Choices]");
slDoc.SetCellValue(1, 4, "[Choices]");
slDoc.SetCellValue(1, 5, "[Tagging Correct Answer]");

int questionCnt = 1;

foreach (var q in detailList.ExamQuestions)
{
   char ltr = 'a';

   slDoc.SetCellValue(rowCtr, 1, questionCnt++);
   slDoc.SetCellValue(rowCtr, 2, q.question);

   foreach (var c in detailList.ExamChoices.Where(x => x.question_id == q.question_id).OrderBy(x => x.orderNo))
   {
       slDoc.SetCellValue(rowCtr, 3, ltr.ToString());
       slDoc.SetCellValue(rowCtr, 4, c.choice);
       slDoc.SetCellValue(rowCtr, 5, c.answer_state ? 1 : 0);

       ltr++;
       rowCtr++;
   }
}

slDoc.SaveAs(ms);
ms.Position = 0;

FileStreamResult file = new FileStreamResult(ms, "text/csv")
{
    FileDownloadName = string.Concat(detailList.exam_module_value, ".csv")
};

using (var fileStream = System.IO.File.Create(Server.MapPath(string.Concat(examPath, "/", detailList.exam_module_value, ".csv"))))
{      
     file.FileStream.Seek(0, SeekOrigin.Begin);
     file.FileStream.CopyTo(fileStream);
     file.FileStream.Seek(0, SeekOrigin.Begin); //reset position to beginning. If there's any chance the FileResult will be used by a future method, this will ensure it gets left in a usable state
}

ms.Close();

【问题讨论】:

  • 虽然您可能已将其命名为.csv,但该图像显示了实际 xlsx OpenXml 包文件的内容。这就是为什么excel可以毫无问题地处理它。

标签: c# asp.net-mvc csv


【解决方案1】:

使用CSVhelper 创建 csv 文件。

您使用的是创建 excel 文件。尽管我会考虑免费的开源跨平台openxml sdk。电子表格灯在其之上工作,自 2017 年以来未更新。

【讨论】:

    【解决方案2】:

    您正在创建一个 Excel 文档,而不是看起来像的 CSV。

    尝试将扩展名重命名为 .xls 或 .xlsx。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多