如何从asp.net中读取数据库创建.CSV文件?任何人都可以建议我如何在asp.net中创建.CSV文件?
先谢谢。
答案 0 :(得分:5)
请检查: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
}
如果您尝试强制下载始终指定“另存为”,则应将content-type设置为application / octet-stream。
<强> 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 (继承自FileHelperEngine)已重载。写一个数组 记录到指定的文件。
WriteStream (继承自FileHelperEngine)已重载。写一个记录数组到 指定的流。
WriteString (继承自 FileHelperEngine)已重载。将一组记录写入String 并将其归还。
参考:
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#
答案 1 :(得分:0)
您可以在文章Reading and Writing CSV Files in C#中了解如何创建CSV文件。
您可以在文章Creating Downloadable Content Dynamically中看到如何动态生成文件内容,但其行为类似于可下载文件。
答案 2 :(得分:0)
为什么你不能这样做:
1)查询数据库(例如,使用SQL阅读器),
2)将您的HTTP响应头(response.ContentType)设置为MIME类型“application / csv”
3)以逗号分隔(CSV)格式写出(response.Write)结果集的每一行?
以下是这种方法的一个例子:
答案 3 :(得分:0)
试试这个:
string filePath = @"C:\test.csv";
string delimiter = ",";
string[][] output = new string[][]{
new string[]{"Col 1 Row 1", "Col 2 Row 1", "Col 3 Row 1"},
new string[]{"Col1 Row 2", "Col2 Row 2", "Col3 Row 2"}
};
int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
sb.AppendLine(string.Join(delimiter, output[index]));
File.WriteAllText(filePath, sb.ToString());
了解更多Help。
答案 4 :(得分:0)
无论如何,如果您允许双引号,逗号,空格等特殊字符出现在您的文件中,您应该找到任何强大的CSV库。
答案 5 :(得分:0)
认为您正在寻找格式的CSV文件。它实际上是一个普通的文本文件,具有非常简单的结构。 You can refer Wiki here。
您可以通过从数据库获取数据并自行制作。根据需要将数据写入文本文件。
以下是CSV文件内容的示例:
Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar
文件中有3列:Year
,Make
,Model
,以及2行数据:1997,Ford,E350
,2000,Mercury,Cougar
。