gpt4 book ai didi

c# - 如何在 asp.net 中创建 .csv 文件?

转载 作者:太空狗 更新时间:2023-10-30 01:07:08 25 4
gpt4 key购买 nike

如何通过在 asp.net 中读取数据库来创建 .CSV 文件?有人可以建议我如何在 asp.net 中创建 .CSV 文件吗?

提前致谢。

最佳答案

检查这个:Exporting DataTable to CSV File Format

public void CreateCSVFile(DataTable dt, string strFilePath)    
{
#region Export Grid to CSV

// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);

// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
int iColCount = dt.Columns.Count;

for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);

// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();

#endregion
}

如果您试图强制下载始终提供另存为,您应该将内容类型设置为应用程序/八位字节流。

Source:

 string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");

var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
sb.AppendLine(TransformDataLineIntoCsv(line));

HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End();

One of the simplest正在使用 FileHelpers Library

FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);

WriteFile (inherited from FileHelperEngine) Overloaded. Write an array of records to the specified file.

WriteStream (inherited fromFileHelperEngine) Overloaded. Write an array of records to the specified Stream.

WriteString (inherited from FileHelperEngine) Overloaded. Write an array of records to an String and return it.

引用:
Write to CSV file and export it?
Export Data to a Comma Delimited (CSV) File for an Application Like Excel
export datatable to CSV with Save File Dialog box - C#

关于c# - 如何在 asp.net 中创建 .csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13410835/

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