繁体   English   中英

创建CSV文件会生成损坏的数据

[英]Creating CSV file generates corrupted data

我有事。 创建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();

高强

文本编辑器

使用CSVhelper创建CSV文件。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM