C#实现将数据导出到word或者Excel中的方法
程序员文章站
2023-11-12 15:41:52
本文实例讲述了c#实现将数据导出到word或者excel中的方法。分享给大家供大家参考。具体如下:
void outtoword()
{
if (datag...
本文实例讲述了c#实现将数据导出到word或者excel中的方法。分享给大家供大家参考。具体如下:
void outtoword() { if (datagridview1.rows.count >= 1) { string tempstr =""; stream mystream; savefiledialog dlg =new savefiledialog(); dlg.filter = "(word文件)*.doc|*.doc"; //dlg.filter = "(word文件)*.xls|*.xls"; dlg.filterindex = 2; dlg.restoredirectory = true; if (dlg.showdialog() ==dialogresult.ok) { if ((mystream = dlg.openfile()) !=null) { streamwriter sw =new streamwriter(mystream,encoding.getencoding("gb2312")); string str =""; try { for (int i = 0; i < datagridview1.columncount; i++) { if (i > 0) str +="\t\t"; str += datagridview1.columns[i].headertext; } sw.writeline(str); for (int j = 0; j < datagridview1.rows.count - 1; j++) { tempstr = ""; for (int k = 0; k < datagridview1.columns.count; k++) { if (k > 0) tempstr +="\t\t"; tempstr += datagridview1.rows[j].cells[k].value.tostring(); } sw.writeline(tempstr); } sw.close(); mystream.close(); messagebox.show("已将信息导出到word","提示"); } catch (exception ex) { messagebox.show(ex.tostring()); } finally { sw.close(); mystream.close(); } } } }
希望本文所述对大家的c#程序设计有所帮助。