永发信息网

C#怎样合并行,列的Excel-CSDN论坛

答案:2  悬赏:10  手机版
解决时间 2021-01-25 07:32
  • 提问者网友:孤山下
  • 2021-01-25 00:33
C#怎样合并行,列的Excel-CSDN论坛
最佳答案
  • 五星知识达人网友:酒者煙囻
  • 2021-01-25 01:39
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 
            Microsoft.Office.Interop.Excel._Worksheet ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
            ws = (Microsoft.Office.Interop.Excel._Worksheet)excel.ActiveSheet;          
            Microsoft.Office.Interop.Excel.Range r;
            r = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 2]);     //合并
全部回答
  • 1楼网友:骨子里都是戏
  • 2021-01-25 02:24
com组件的方式读取excel : 这种方式需要先引用 microsoft.office.interop.excel 。首选说下这种方式的优缺点 优点:可以非常灵活的读取excel中的数据 缺点:如果是web站点部署在iis上时,还需要服务器机子已安装了excel,有时候还需要为配置iis权限。最重要的一点因为是基于单元格方式读取的,所以数据很慢。 代码如下: datatable getdatafromexcelbycom(bool hastitle = false) { openfiledialog openfile = new openfiledialog(); openfile.filter = "excel(*.xlsx)|*.xlsx|excel(*.xls)|*.xls"; openfile.initialdirectory = environment.getfolderpath(environment.specialfolder.desktop); openfile.multiselect = false; if (openfile.showdialog() == dialogresult.cancel) return null; var excelfilepath = openfile.filename; excel.application app = new excel.application(); excel.sheets sheets; object omissiong = system.reflection.missing.value; excel.workbook workbook = null; datatable dt = new datatable(); try { if (app == null) return null; workbook = app.workbooks.open(excelfilepath, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong, omissiong); sheets = workbook.worksheets; //将数据读入到datatable中 excel.worksheet worksheet = (excel.worksheet)sheets.get_item(1);//读取第一张表 if (worksheet == null) return null; int irowcount = worksheet.usedrange.rows.count; int icolcount = worksheet.usedrange.columns.count; //生成列头 for (int i = 0; i < icolcount; i++) { var name = "column" + i; if (hastitle) { var txt = ((excel.range)worksheet.cells[1, i + 1]).text.tostring(); if (!string.isnullorwhitespace(txt)) name = txt; } while (dt.columns.contains(name)) name = name + "_1";//重复行名称会报错。 dt.columns.add(new datacolumn(name, typeof(string))); } //生成行数据 excel.range range; int rowidx = hastitle ? 2 : 1; for (int irow = rowidx; irow <= irowcount; irow++) { datarow dr = dt.newrow(); for (int icol = 1; icol <= icolcount; icol++) { range = (excel.range)worksheet.cells[irow, icol]; dr[icol - 1] = (range.value2 == null) ? "" : range.text.tostring(); } dt.rows.add(dr); } return dt; } catch { return null; } finally { workbook.close(false, omissiong, omissiong); system.runtime.interopservices.marshal.releasecomobject(workbook); workbook = null; app.workbooks.close(); app.quit(); system.runtime.interopservices.marshal.releasecomobject(app); app = null; } }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯