首页 > 解决方案 > 创建 CSV 文件会生成损坏的数据

问题描述

我有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();

Excel

文本编辑器

标签: c#asp.net-mvccsv

解决方案


使用CSVhelper创建 csv 文件。

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


推荐阅读