【发布时间】: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