gpt4 book ai didi

c# - 导出到 .csv 文件

转载 作者:行者123 更新时间:2023-11-30 17:08:20 24 4
gpt4 key购买 nike

我在将数据导出到 .csv 文件时遇到问题。我使用 2 种方法。

        Encoding csvEncoding = new UTF8SignatureEncoding();
byte[] csvFile = TestByte(CsvContentDelimiter.NewLine, CsvContentDelimiter.Semicolon, csvEncoding);


string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();

    public byte[] TestByte(CsvContentDelimiter rowDelimiter, CsvContentDelimiter columnDelimiter, Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.Append("product;");
return encoding.GetBytes(sb.ToString());
}

此代码创建 .csv 文件,但文件编码错误,我只看到一些“哈希”

最佳答案

这是一个使用 UTF8 格式的完整示例。它使用您自己的代码,因此表明是您的编码导致了问题:

namespace WebApplication1
{
using System;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
protected void btnExport_Click(object sender, EventArgs e)
{
// Use UTF8 encoding
Encoding csvEncoding = Encoding.UTF8;
byte[] csvFile = TestByte(csvEncoding);

string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
}

public byte[] TestByte(Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Record1,Fred,Bloggs,26{0}", Environment.NewLine);
sb.AppendFormat("Record2,John,Smith,32{0}", Environment.NewLine);
return encoding.GetBytes(sb.ToString());
}
}
}

关于c# - 导出到 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13840450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com