[英]Exporting datagridview to csv file
我正在開發一個將名為scannerDataGridView 的DataGridView 導出到csv 文件的應用程序。
找到了一些示例代碼來執行此操作,但無法使其正常工作。 順便說一句,我的數據網格沒有數據綁定到源。
當我嘗試使用 Streamwriter 僅寫入列標題時,一切順利,但是當我嘗試導出包括數據在內的整個數據網格時,我得到了一個例外。
System.NullReferenceException:對象引用未設置為對象的實例。 在 Scanmonitor.Form1.button1_Click(對象發送者,EventArgs e)
這是我的代碼,以下行給出了錯誤:
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
//csvFileWriter = StreamWriter
//scannerDataGridView = DataGridView
private void button1_Click(object sender, EventArgs e)
{
string CsvFpath = @"C:\scanner\CSV-EXPORT.csv";
try
{
System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
string columnHeaderText = "";
int countColumn = scannerDataGridView.ColumnCount - 1;
if (countColumn >= 0)
{
columnHeaderText = scannerDataGridView.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + scannerDataGridView.Columns[i].HeaderText;
}
csvFileWriter.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in scannerDataGridView.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
csvFileWriter.WriteLine(dataFromGrid);
}
}
}
csvFileWriter.Flush();
csvFileWriter.Close();
}
catch (Exception exceptionObject)
{
MessageBox.Show(exceptionObject.ToString());
}
LINQ FTW!
var sb = new StringBuilder();
var headers = dataGridView1.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>();
sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
實際上, c.Value.ToString()
將拋出空值,而c.Value
將正確轉換為空字符串。
DataGridView
的一個鮮為人知的功能是能夠以編程方式選擇部分或全部 DataGridCell,並使用DataGridView.GetClipboardContent()
方法將它們發送到DataObject
。 那這有什么好處呢?
DataObject
不只是存儲一個對象,而是以各種不同格式表示該對象。 這就是剪貼板能夠發揮其魔力的方式; 它存儲了各種格式,不同的控件/類可以指定他們希望接受的格式。 在這種情況下,DataGridView 會將 DataObject 中的選定單元格存儲為制表符分隔的文本格式、CSV 格式或 HTML (*)。
可以通過調用DataObject.GetData()
或DataObject.GetText()
方法並指定預定義的數據格式枚舉來檢索 DataObject 的內容。 在這種情況下,我們希望 CSV 的格式為 TextDataFormat.CommaSeparatedValue,然后我們可以使用System.IO.File
類將該結果寫入文件。
(*) 實際上,嚴格來說,它返回的不是 HTML。 此格式還將包含您不期望的數據標題。 雖然標題確實包含 HTML 的起始位置,但我只是丟棄了 HTML 標記上方的任何內容,例如myString.Substring(IndexOf("<HTML>"));
.
觀察以下代碼:
void SaveDataGridViewToCSV(string filename)
{
// Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
// Select all the cells
dataGridView1.SelectAll();
// Copy selected cells to DataObject
DataObject dataObject = dataGridView1.GetClipboardContent();
// Get the text of the DataObject, and serialize it to a file
File.WriteAllText(filename, dataObject.GetText(TextDataFormat.CommaSeparatedValue));
}
現在,不是更好嗎? 為什么要重新發明輪子?
希望這可以幫助...
我知道這可能已經死了但是我做了一個簡單的代碼,它根據DataGridView對象創建一個CSV並詢問你想要保存它的位置。
它很直接,只需粘貼功能並使用它。 它已經有一些基本的異常處理,所以使用起來非常安全。 請享用。
private void SaveToCSV(DataGridView DGV)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Output.csv";
if (sfd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Data will be exported and you will be notified when it is ready.");
if (File.Exists(filename))
{
try
{
File.Delete(filename);
}
catch (IOException ex)
{
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
int columnCount = DGV.ColumnCount;
string columnNames = "";
string[] output = new string[DGV.RowCount + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += DGV.Columns[i].Name.ToString() + ",";
}
output[0] += columnNames;
for (int i = 1; (i - 1) < DGV.RowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
output[i] += DGV.Rows[i - 1].Cells[j].Value.ToString() + ",";
}
}
System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
MessageBox.Show("Your file was generated and its ready for use.");
}
}
編輯:改變了';' 到','因為我們在討論CSV文件
Please check this code.its working fine
try
{
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
//Add the Header row for CSV file.
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
csv += column.HeaderText + ',';
}
//Add new line.
csv += "\r\n";
//Adding the Rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value != null)
{
//Add the Data rows.
csv += cell.Value.ToString().TrimEnd(',').Replace(",", ";") + ',';
}
// break;
}
//Add new line.
csv += "\r\n";
}
//Exporting to CSV.
string folderPath = "C:\\CSV\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
File.WriteAllText(folderPath + "Invoice.csv", csv);
MessageBox.Show("");
}
catch
{
MessageBox.Show("");
}
您的代碼幾乎就在那里......但我做了以下更正,效果很好。 謝謝你的帖子。
錯誤:
string[] output = new string[dgvLista_Apl_Geral.RowCount + 1];
更正:
string[] output = new string[DGV.RowCount + 1];
錯誤:
System.IO.File.WriteAllLines(filename, output, System.Text.Encoding.UTF8);
更正:
System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
發現了問題,編碼很好,但我有一個空單元格出現了問題。
行“csvFileWriter.WriteLine(dataFromGrid);” 應該在右括號下方向下移動一行,否則你會得到很多重復的結果:
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
}
csvFileWriter.WriteLine(dataFromGrid);
我認為這對您的 SaveToCSV 函數是正確的:(否則為 Null ...)
for (int i = 0; i < columnCount; i++)
不是 :
for (int i = 1; (i - 1) < DGV.RowCount; i++)
這是我在項目中使用的:
void export_csv(string file, DataGridView grid)
{
using (StreamWriter csv = new StreamWriter(file, false))
{
int totalcolms = grid.ColumnCount;
foreach (DataGridViewColumn colm in grid.Columns) csv.Write(colm.HeaderText + ',');
csv.Write('\n');
string data = "";
foreach (DataGridViewRow row in grid.Rows)
{
if (row.IsNewRow) continue;
data = "";
for (int i = 0; i < totalcolms; i++)
{
data += (row.Cells[i].Value ?? "").ToString() + ',';
}
if (data != string.Empty) csv.WriteLine(data);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.