0

StringWriter在我们的应用程序上使用时遇到问题。我对 a 进行了一次休息调用 nosql db,它返回了一个dynamics. 我StringWriter用来编写一个csv文件,其中包含我列表中的标题和记录。

我还尝试sealed class使用constructor method允许您输入编码类型作为参数的 StringWriter 来扩展 StringWriter。但是尝试所有可用的编码仍然会生成错误的字符。

这是我们对 StringWriter 的扩展:

public sealed class StringWriterWithEncoding : StringWriter
{
    private readonly Encoding encoding;

    public StringWriterWithEncoding() : this(Encoding.UTF8) { }

    public StringWriterWithEncoding(Encoding encoding)
    {
        this.encoding = encoding;
    }

    public override Encoding Encoding
    {
        get { return encoding; }
    }
}

这是生成 csv 文件的代码:

StringWriterWithEncoding sw = new StringWriterWithEncoding();

// Header
sw.WriteLine(string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};", "Soddisfazione", "Data Ricerca", "Categorie Cercate", "Id Utente", "Utente", "Categoria", "Id Documento", "Documento", "Id Sessione", "Testo Ricerca"));

foreach (var item in result.modelListDyn)
{
   sw.WriteLine(string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};", item.Satisfaction, item.Date, item.Cluster, item.UserId, item.Username, item.Category, item.DocumentId, HttpUtility.HtmlDecode(item.DocumentTitle.ToString()), item.SessionId, 
   item.TextSearch));
}

var response = Request.CreateResponse(HttpStatusCode.OK, sw.ToString());

response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

return response;

当文件在带有一些文本的列中生成时,它会显示奇怪的字符: L’indennità di licenziamento del Jobs Act è incostituzionale

这是意大利语,错误的字符似乎是à è ò ' ù等等。

任何人都可以提出解决方案吗?谢谢!

更新

正如用户建议的那样,我开始使用 CsvHelper 我创建了一个 Class 和一个 ClassMap 但它仍然返回损坏的字符。

StringWriter sw = new StringWriter();
CsvWriter cw = new CsvWriter(sw);
using (CsvWriter csv = new CsvWriter(sw))
{
  csv.Configuration.RegisterClassMap<HistorySearchModelCsvHelperMap>();
  csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
  csv.WriteRecords(csvModelHelperList);
}

结果: 在此处输入图像描述

更新 2

问题是client-side,我的操作返回正确的文本,没有损坏的字符。axios当我用get 实例调用它时,就会触发动作。

axios.get(url, {
   headers: {
      'Accept': 'application/vnd.ms-excel',
      'Content-Type': 'application/vnd.ms-excel'
   }
})
.then(({ data }) => {
   const blob = new Blob([data], {
      type: 'application/vnd.ms-excel',
   });
   // "fileDownload" is 'js-file-download' module.
   fileDownload(blob, 'HistorySearches.csv', 'application/vnd.ms-excel');
   this.setState({ exportLoaded: true, exportLoading: false });
}).catch(() => {
   this.setState({ exportLoaded: false, exportLoading: false });
});

我读到设置但即使responseType传递blob类型:'application/vnd.ms-excel' 我的 csv 文件上的字符仍然损坏。在我action返回时Response

// ... some code

StringWriterWithEncoding sw = new StringWriterWithEncoding();
CsvWriter cw = new CsvWriter(sw);
using (CsvWriter csv = new CsvWriter(sw))
{
    csv.Configuration.RegisterClassMap<HistorySearchModelCsvHelperMap>();
    csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
    csv.WriteRecords(csvModelHelperList);
}

return Request.CreateResponse(HttpStatusCode.OK, sw.ToString());
// response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.ms-excel");

return response;

我也尝试设置内容类型服务器端,但格式不正确。

4

2 回答 2

0

如果您希望能够在 Excel 中打开您的 csv,您需要使用 Windows-1255 的编码编写它。

如果您在通用文本编辑器中打开 csv,但它仍然显示不正确,我不确定出了什么问题,因为您的代码看起来很正常。

于 2019-10-04T14:38:53.820 回答
0

直接解决client-side了。我制作了自己的下载例程并传递了UTF-8 BOM响应字符串的第一个值:

downloadFile2(data, fileName, type="text/string") {
    // Create an invisible A element
    const a = document.createElement("a");
    a.style.display = "none";

    // Using "universal BOM" https://technet.microsoft.com/en-us/2yfce773(v=vs.118)
    const universalBOM = "\uFEFF";
    a.setAttribute('href', 'data:text/csv; charset=utf-8,' + encodeURIComponent(universalBOM+data));
    // Use download attribute to set set desired file name
    a.setAttribute('download', fileName);
    document.body.appendChild(a);
    // Trigger the download by simulating click
    a.click();

    // Cleanup
    window.URL.revokeObjectURL(a.href);
    document.body.removeChild(a);
},
于 2019-11-25T12:02:03.283 回答