C# Winform实现导入和导出Excel文件
程序员文章站
2023-12-14 09:59:58
本文实例为大家分享了winform实现导入导出excel文件的具体代码,供大家参考,具体内容如下
///
/// 导出e...
本文实例为大家分享了winform实现导入导出excel文件的具体代码,供大家参考,具体内容如下
/// <summary> /// 导出excel文件 /// </summary> /// /// <param name="dataset"></param> /// <param name="datatable">数据集</param> /// <param name="isshowexcle">导出后是否打开文件</param> /// <returns></returns> public static bool datatabletoexcel(string filepath, system.data.datatable datatable, bool isshowexcle) { //system.data.datatable datatable = dataset.tables[0]; int rownumber = datatable.rows.count; int columnnumber = datatable.columns.count; int colindex = 0; if (rownumber == 0) { return false; } microsoft.office.interop.excel.application excel = new microsoft.office.interop.excel.application(); microsoft.office.interop.excel.workbook workbook = excel.workbooks.add(microsoft.office.interop.excel.xlwbatemplate.xlwbatworksheet); microsoft.office.interop.excel.worksheet worksheet = (microsoft.office.interop.excel.worksheet)workbook.worksheets[1]; excel.visible = isshowexcle; microsoft.office.interop.excel.range range; foreach (datacolumn col in datatable.columns) { colindex++; excel.cells[1, colindex] = col.columnname; } object[,] objdata = new object[rownumber, columnnumber]; for (int r = 0; r < rownumber; r++) { for (int c = 0; c < columnnumber; c++) { objdata[r, c] =datatable.rows[r][c]; } } range = worksheet.get_range(excel.cells[2, 1], excel.cells[rownumber + 1, columnnumber]); range.value2 = objdata; range.numberformatlocal = "@"; worksheet.saveas(filepath, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing); //excel.quit(); return true; }
读取excel文件数据到datatable
/// <summary> /// 读取excel文件数据到datatable /// </summary> /// <param name="filepath">excel文件路径</param> private void import_excel(string filepath) { string sqlconn = "provider=microsoft.jet.oledb.4.0;data source=" + filepath + ";extended properties='excel 8.0;hdr=false;imex=1'"; string sql = @"select * from [sheet1$]"; try { using (oledbconnection conn = new oledbconnection(sqlconn)) { using (oledbdataadapter adapter = new oledbdataadapter(sql, conn)) { system.data.datatable dt = new system.data.datatable(); adapter.fill(dt); this.loaddatagridview(dt); } } } catch (exception ex) { messagebox.show("打开文件出错,错误信息:" + ex.message.tostring(), "提示"); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
-
C# Winform实现导入和导出Excel文件
-
C# 文件上传下载(Excel导入,多线程下载)功能的实现代码
-
C#实现导入CSV文件到Excel工作簿的方法
-
C# Winform实现导入和导出Excel文件
-
php实现CSV文件导入和导出
-
C#实现导入CSV文件到Excel工作簿的方法
-
【C#常用方法】2.DataTable(或DataSet)与Excel文件之间的导出与导入(使用NPOI)
-
C#实现DataSet内数据转化为Excel和Word文件的通用类完整实例
-
Laravel Excel 实现 Excel-CSV 文件导入导出功能
-
结合bootstrap fileinput插件和Bootstrap-table表格插件,实现文件上传、预览、提交的导入Excel数据操作流程