c# - 创建 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();
解决方案
使用CSVhelper创建 csv 文件。
您使用的是创建 excel 文件。即使我会考虑免费的开源跨平台openxml sdk。电子表格灯在其之上工作,自 2017 年以来未更新。
推荐阅读
- javascript - 如何将变量从 c# 传递到 javascript 以在 plotly.js 中绘图
- python - SQL alchemy 对 LIMIT 查询应用默认过滤器
- tensorflow - 如何在不考虑方差的情况下去除 Keras 层的均值,例如 Batchnormalization?
- reactjs - 是否可以有条件地仅在 React 的输入标签中呈现占位符属性?
- amazon-web-services - 在 Athena 中查询表时获取 HIVE_CURSOR_ERROR
- python - tkinter 滚动条在调整窗口大小之前处于非活动状态
- rust - 将 TaskManager 脚本从 gdscript/Godot 迁移到 bevy 和 rust
- python-3.x - 如何在 python 3 中通过查看断言正则表达式来处理可变长度数字序列
- python - Python获取Speech to text语音音频数据
- python - SQL忽略带有WHERE IN UNNEST子句的空数组