winfrom数据导出
/// <summary>
/// 数据导出
/// </summary>
/// <param name="datagridview"></param>
/// <returns></returns>
private bool datagridviewtocsv(datagridview datagridview)
{
if (datagridview.rows.count == 0)
{
messagebox.show("没有数据可导出!", "提示", messageboxbuttons.ok, messageboxicon.information);
return false;
}
savefiledialog savefiledialog = new savefiledialog();
savefiledialog.filter = "csv files (*.csv)|*.csv";
savefiledialog.filterindex = 0;
savefiledialog.restoredirectory = true;
savefiledialog.createprompt = true;
savefiledialog.filename = null;
savefiledialog.title = "保存";
datetime now = datetime.now;
savefiledialog.filename = now.year.tostring().padleft(2)
+ now.month.tostring().padleft(2, '0')
+ now.day.tostring().padleft(2, '0') + "-"
+ now.hour.tostring().padleft(2, '0')
+ now.minute.tostring().padleft(2, '0')
+ now.second.tostring().padleft(2, '0');
if (savefiledialog.showdialog() == dialogresult.ok)
{
stream stream = savefiledialog.openfile();
streamwriter sw = new streamwriter(stream, system.text.encoding.getencoding(-0));
string strline = "";
try
{
//表头
for (int i = 0; i < datagridview.columncount; i++)
{
if (i > 0)
strline += ",";
strline += datagridview.columns[i].headertext;
}
strline.remove(strline.length - 1);
sw.writeline(strline);
strline = "";
//表的内容
for (int j = 0; j < datagridview.rows.count; j++)
{
strline = "";
int colcount = datagridview.columns.count;
for (int k = 0; k < colcount; k++)
{
if (k > 0 && k < colcount)
strline += ",";
if (datagridview.rows[j].cells[k].value == null)
strline += "";
else
{
string cell = datagridview.rows[j].cells[k].value.tostring().trim();
//防止里面含有特殊符号
cell = cell.replace("\"", "\"\"");
cell = "\"" + cell + "\"";
strline += cell;
}
}
sw.writeline(strline);
}
sw.close();
stream.close();
messagebox.show("数据被导出到:" + savefiledialog.filename.tostring(), "导出完毕", messageboxbuttons.ok, messageboxicon.information);
}
catch (exception ex)
{
messagebox.show(ex.message, "导出错误", messageboxbuttons.ok, messageboxicon.information);
return false;
}
}
return true;
}
上一篇: 对python .txt文件读取及数据处理方法总结
下一篇: C#中多线程中变量研究