Winform DataGridView复制表格内容为CSV
csv内容可直接复制到微软Excel表格中,wps这么复制是不支持的,用原生DataGridView复制方式即可两种办公软件都兼容,csv方式仅作笔记。
核心代码:
private void btnCopy_Click(object sender, EventArgs e) { try { var csv = (DataGridView1.ToDataTable()).ToCsv(); var bytes = System.Text.Encoding.Default.GetBytes(csv); //必须转码 using (var stream = new System.IO.MemoryStream(bytes)) Clipboard.SetData(System.Windows.Forms.DataFormats.CommaSeparatedValue, stream);
//DataGridView自带复制粘贴方式
//dg.SelectAll();
//Clipboard.SetDataObject(dg.GetClipboardContent());
//dg.ClearSelection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
static class Extentions { /// <summary> /// DataTable转Csv /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToCsv(this DataTable dt) { StringBuilder builder = new StringBuilder(); IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().Select(column => string.IsNullOrWhiteSpace(column.Caption) ? column.ColumnName : column.Caption); builder.AppendLine(string.Join(",", columnNames)); foreach (DataRow row in dt.Rows) { IEnumerable<string> fields = row.ItemArray.Select(field => { string s = field.ToString().Replace("\"", "\"\""); if (s.Contains(',')) s = string.Concat("\"", s, "\""); return s; }); builder.AppendLine(string.Join(",", fields)); } return builder.ToString().Trim(); } /// <summary> /// 将DataGridView里面的数据提取到DataTable中 /// </summary> /// <param name="dataGridView"></param> /// <returns></returns> public static DataTable ToDataTable(this DataGridView dataGridView) { var dataTable = new DataTable(); for (var i = 0; i < dataGridView.RowCount; i++) { var dr = dataTable.NewRow(); for (var j = 0; j < dataGridView.ColumnCount; j++) { if (i == 0) { var dc = new DataColumn(dataGridView.Columns[j].Name); dc.Caption = dataGridView.Columns[j].HeaderText; dataTable.Columns.Add(dc); } dr[j] = dataGridView[j, i].Value; } dataTable.Rows.Add(dr); } return dataTable; } }