[英]How can I create schema.ini file? I need to export my .csv file to datagridview
[英]How to export my DataGridView to a csv file?
我正在嘗試使用以下代碼將DataGridView
導出到csv
文件:
private void saveToCsv(DataGridView dGV, string filename)
{
if (dGV.RowCount > 0)
{
DataTable dt = new DataTable();
dt = dGV.DataSource as DataTable;
int d = dt.Columns.Count;
int c = dt.Rows.Count;
foreach (var column in dt.Columns.Cast<DataColumn>().ToArray())
{
if (dt.AsEnumerable().All(dr => dr.IsNull(column)))
d--;
}
string stOutput = "";
DataGridViewRow ds = new DataGridViewRow();
StreamWriter swOut = new StreamWriter(filename);
//write header rows to csv
for (int i = 0; i <= d - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
swOut.Write(dGV.Columns[i].HeaderText);
}
swOut.WriteLine();
//write DataGridView rows to csv
for (int j = 0; j <= c - 1; j++)
{
if (dt.Rows[j].IsNull)
if (j > 0)
{
swOut.WriteLine();
}
ds = dGV.Rows[j];
for (int i = 0; i <= d - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
stOutput = ds.Cells[i].Value.ToString();
//replace comma's with spaces
stOutput = stOutput.Replace(',', ' ');
//replace embedded newlines with spaces
stOutput = stOutput.Replace(Environment.NewLine, " ");
swOut.Write(stOutput);
}
}
swOut.Close();
}
MessageBox.Show("Data successfully saved");
}
但是輸出是這樣的:
0.512,45,tested_negative 0.966,33,tested_negative 0.42,35,tested_negative 0.665,46,tested_positive 0.329,29,tested_negative ,, ,, ,, ,, ,, ,, ,, ,,
空行也將導出。
我該如何解決這個問題?
首先,如果要創建逗號分隔的文件,則應限制文本數據的大小寫,以防它們中包含逗號
取自stackoverflow(請參閱將datagridview導出到csv文件 )
var sb = new StringBuilder();
var headers = dGV.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var cells = row.Cells.Cast<DataGridViewCell>();
string temp string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray())
temp = temp.Replace(",","");
temp = temp.Replace("\"","");
if(temp.Length > 0)
{
sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
}
System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\test\hereIam.csv");
file.WriteLine(sb.ToString()); //
如果要堅持使用代碼,請檢查stOutput
如果它是',,'
請不要將其寫入文件中。
您可能要檢查https://stackoverflow.com/a/4959869/7505395-C#數據表 到CSV的答案之一
// ... your code ...
if ( stOutput != ",,")
swOut.Write(stOutput);
else suppressNewLine = true; // suppress newline above, and reset bool to false
// ... more of your code ...
之后,您必須修復空白的換行符。
最好的辦法是將每行(或整個表gasp )組裝到StringBuilder
-並在完全組裝(行或整個表)時僅一次(或至少逐行)地將其寫入文件。
StringBuilders是為向其迭代添加而構建的,應該使您的代碼更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.