Excel导入到DataTable ,DataTable导入到Excel
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using NPOI.SS.UserModel;
- using NPOI.XSSF.UserModel;
- using NPOI.HSSF.UserModel;
- using System.IO;
- using System.Data;
- using NPOI.SS.Util;
- using NPOI.HSSF.Util;// 列
- namespace Common.Utility
- {
- public class ExcelHelper : IDisposable
- {
- private string fileName = null; //文件名
- private IWorkbook workbook = null;
- private FileStream fs = null;
- private bool disposed;
- public ExcelHelper(string fileName)
- {
- this.fileName = fileName;
- disposed = false;
- }
- /// <summary>
- /// 将DataTable数据导入到excel中
- /// </summary>
- /// <param name="data">要导入的数据</param>
- /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
- /// <param name="sheetName">要导入的excel的sheet的名称</param>
- /// <returns>导入数据行数(包含列名那一行)</returns>
- public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten,string args="")
- {
- int i = 0;
- int j = 0;
- int count = 0;
- ISheet sheet = null;
- fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- if (fileName.IndexOf(".xlsx") > 0) // 2007版本
- workbook = new XSSFWorkbook();
- else if (fileName.IndexOf(".xls") > 0) // 2003版本
- workbook = new HSSFWorkbook();
- try
- {
- if (workbook != null)
- {
- sheet = workbook.CreateSheet(sheetName);
- }
- else
- {
- return -1;
- }
- if (isColumnWritten == true) //写入DataTable的列名
- {
- IRow row = sheet.CreateRow(0);
- for (j = 0; j < data.Columns.Count; ++j)
- {
- row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
- }
- count = 1;
- }
- else
- {
- count = 0;
- }
- for (i = 0; i < data.Rows.Count; ++i)
- {
- IRow row = sheet.CreateRow(count);
- for (j = 0; j < data.Columns.Count; ++j)
- {
- row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
- if (args == "export_code" && data.Rows[i][j].ToString()=="合计")
- {
- SetCellRangeAddress(sheet, i + 1, i + 1, 0, 3);
- IRow row_1 = sheet.GetRow(i + 1);
- ICell cell = row_1.GetCell(0);
- ICellStyle cellstyle = workbook.CreateCellStyle();//设置垂直居中格式
- cellstyle.VerticalAlignment = VerticalAlignment.Justify;//垂直居中
- cellstyle.Alignment = HorizontalAlignment.Center;
- cell.CellStyle = cellstyle;
- }
- }
- ++count;
- }
- if (args == "export_code")
- {
- var oldCode = "";
- int n = 0;
- for (i = 0; i < data.Rows.Count; ++i)
- {
- var code = data.Rows[i][1];
- if (oldCode == "")
- {
- oldCode = code.ToString();
- n = i;
- }
- if (oldCode != code.ToString())
- {
- SetCellRangeAddress(sheet, n + 1, i, 1, 1);
- IRow row = sheet.GetRow(n + 1);
- ICell cell = row.GetCell(1);
- ICellStyle cellstyle = workbook.CreateCellStyle();//设置垂直居中格式
- cellstyle.VerticalAlignment = VerticalAlignment.Justify;//垂直居中
- cellstyle.Alignment = HorizontalAlignment.Center;
- cell.CellStyle = cellstyle;
- }
- if (data.Rows[i][4].ToString() == "合计")
- {
- oldCode = "";
- }
- }
- }
- workbook.Write(fs); //写入到excel
- return count;
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception: " + ex.Message);
- return -1;
- }
- }
- #region
- /// <summary>
- /// 获取单元格样式
- /// </summary>
- /// <param name="hssfworkbook">Excel操作类</param>
- /// <param name="font">单元格字体</param>
- /// <param name="fillForegroundColor">图案的颜色</param>
- /// <param name="fillPattern">图案样式</param>
- /// <param name="fillBackgroundColor">单元格背景</param>
- /// <param name="ha">垂直对齐方式</param>
- /// <param name="va">垂直对齐方式</param>
- /// <returns></returns>
- public static ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook, HSSFColor fillBackgroundColor, HorizontalAlignment ha, VerticalAlignment va)
- {
- ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
- cellstyle.Alignment = ha;
- cellstyle.VerticalAlignment = va;
- if (fillBackgroundColor != null)
- {
- cellstyle.FillBackgroundColor = fillBackgroundColor.GetIndex();
- }
- return cellstyle;
- }
- /// <summary>
- /// 合并单元格
- /// </summary>
- /// <param name="sheet">要合并单元格所在的sheet</param>
- /// <param name="rowstart">开始行的索引</param>
- /// <param name="rowend">结束行的索引</param>
- /// <param name="colstart">开始列的索引</param>
- /// <param name="colend">结束列的索引</param>
- public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
- {
- CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
- sheet.AddMergedRegion(cellRangeAddress);
- }
- #endregion
- /// <summary>
- /// 将excel中的数据导入到DataTable中
- /// </summary>
- /// <param name="sheetName">excel工作薄sheet的名称</param>
- /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
- /// <returns>返回的DataTable</returns>
- public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
- {
- ISheet sheet = null;
- DataTable data = new DataTable();
- int startRow = 0;
- try
- {
- fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
- if (fileName.IndexOf(".xlsx") > 0) // 2007版本
- workbook = new XSSFWorkbook(fs);
- else if (fileName.IndexOf(".xls") > 0) // 2003版本
- workbook = new HSSFWorkbook(fs);
- if (sheetName != null)
- {
- sheet = workbook.GetSheet(sheetName);
- if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
- {
- sheet = workbook.GetSheetAt(0);
- }
- }
- else
- {
- sheet = workbook.GetSheetAt(0);
- }
- if (sheet != null)
- {
- IRow firstRow = sheet.GetRow(0);
- int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
- if (isFirstRowColumn)
- {
- for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
- {
- ICell cell = firstRow.GetCell(i);
- if (cell != null)
- {
- string cellValue = cell.StringCellValue;
- if (cellValue != null)
- {
- DataColumn column = new DataColumn(cellValue);
- data.Columns.Add(column);
- }
- }
- }
- startRow = sheet.FirstRowNum + 1;
- }
- else
- {
- startRow = sheet.FirstRowNum;
- }
- //最后一列的标号
- int rowCount = sheet.LastRowNum;
- ICell tempcell = null;
- for (int i = startRow; i <= rowCount; ++i)
- {
- IRow row = sheet.GetRow(i);
- if (row == null) continue; //没有数据的行默认是null
- DataRow dataRow = data.NewRow();
- for (int j = row.FirstCellNum; j < cellCount; ++j)
- {
- tempcell = row.GetCell(j);
- if (tempcell != null) //同理,没有数据的单元格都默认是null
- {
- switch (tempcell.CellType)
- {
- case CellType.Blank:
- dataRow[j] = "";
- break;
- case CellType.String:
- dataRow[j] = tempcell.StringCellValue;
- break;
- case CellType.Numeric:
- dataRow[j] = tempcell.NumericCellValue;
- break;
- case CellType.Formula:
- dataRow[j] = tempcell.NumericCellValue;
- break;
- default:
- dataRow[j] = "";
- break;
- }
- }
- }
- data.Rows.Add(dataRow);
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception: " + ex.Message);
- throw ex;
- //return null;
- }
- }
- /// <summary>
- /// 将excel中的数据导入到DataTable中,增加多个sheet的情况
- /// </summary>
- /// <param name="sheetName">excel工作薄sheet的名称</param>
- /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
- /// <returns>返回的DataTable</returns>
- public DataTable ExcelToDataTable(int sheetIndex, bool isFirstRowColumn)
- {
- ISheet sheet = null;
- DataTable data = new DataTable();
- int startRow = 0;
- try
- {
- fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
- if (fileName.IndexOf(".xlsx") > 0) // 2007版本
- workbook = new XSSFWorkbook(fs);
- else if (fileName.IndexOf(".xls") > 0) // 2003版本
- workbook = new HSSFWorkbook(fs);
- sheet = workbook.GetSheetAt(sheetIndex);
- if (sheet != null)
- {
- IRow firstRow = sheet.GetRow(0);
- int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
- if (isFirstRowColumn)
- {
- for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
- {
- ICell cell = firstRow.GetCell(i);
- if (cell != null)
- {
- string cellValue = cell.StringCellValue;
- if (cellValue != null)
- {
- DataColumn column = new DataColumn(cellValue);
- data.Columns.Add(column);
- }
- }
- }
- startRow = sheet.FirstRowNum + 1;
- }
- else
- {
- startRow = sheet.FirstRowNum;
- }
- //最后一列的标号
- int rowCount = sheet.LastRowNum;
- ICell tempcell = null;
- for (int i = startRow; i <= rowCount; ++i)
- {
- IRow row = sheet.GetRow(i);
- if (row == null) continue; //没有数据的行默认是null
- DataRow dataRow = data.NewRow();
- for (int j = row.FirstCellNum; j < cellCount; ++j)
- {
- tempcell = row.GetCell(j);
- if (tempcell != null) //同理,没有数据的单元格都默认是null
- {
- switch (tempcell.CellType)
- {
- case CellType.Blank:
- dataRow[j] = "";
- break;
- case CellType.String:
- dataRow[j] = tempcell.StringCellValue;
- break;
- case CellType.Numeric:
- dataRow[j] = tempcell.NumericCellValue;
- break;
- case CellType.Formula:
- dataRow[j] = tempcell.NumericCellValue;
- break;
- default:
- dataRow[j] = "";
- break;
- }
- }
- }
- data.Rows.Add(dataRow);
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception: " + ex.Message);
- throw ex;
- }
- }
- public DataTable ExcelToDataTable(int sheetIndex, int RowIndex, bool isFirstRowColumn)
- {
- ISheet sheet = null;
- DataTable data = new DataTable();
- int startRow = 0;
- try
- {
- fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
- if (fileName.IndexOf(".xlsx") > 0) // 2007版本
- workbook = new XSSFWorkbook(fs);
- else if (fileName.IndexOf(".xls") > 0) // 2003版本
- workbook = new HSSFWorkbook(fs);
- sheet = workbook.GetSheetAt(sheetIndex);
- if (sheet != null)
- {
- IRow firstRow = sheet.GetRow(RowIndex);
- int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
- if (isFirstRowColumn)
- {
- for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
- {
- ICell cell = firstRow.GetCell(i);
- if (cell != null)
- {
- string cellValue = cell.StringCellValue;
- if (cellValue != null)
- {
- DataColumn column = new DataColumn(cellValue);
- data.Columns.Add(column);
- }
- }
- }
- startRow = sheet.FirstRowNum + 1+ RowIndex;
- }
- else
- {
- startRow = sheet.FirstRowNum+ RowIndex;
- }
- //最后一列的标号
- int rowCount = sheet.LastRowNum;
- ICell tempcell = null;
- for (int i = startRow; i <= rowCount; ++i)
- {
- IRow row = sheet.GetRow(i);
- if (row == null) continue; //没有数据的行默认是null
- DataRow dataRow = data.NewRow();
- for (int j = row.FirstCellNum; j < cellCount; ++j)
- {
- tempcell = row.GetCell(j);
- if (tempcell != null) //同理,没有数据的单元格都默认是null
- {
- switch (tempcell.CellType)
- {
- case CellType.Blank:
- dataRow[j] = "";
- break;
- case CellType.String:
- dataRow[j] = tempcell.StringCellValue;
- break;
- case CellType.Numeric:
- dataRow[j] = tempcell.NumericCellValue;
- break;
- case CellType.Formula:
- dataRow[j] = tempcell.NumericCellValue;
- break;
- default:
- dataRow[j] = "";
- break;
- }
- }
- }
- data.Rows.Add(dataRow);
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception: " + ex.Message);
- throw ex;
- }
- }
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- protected virtual void Dispose(bool disposing)
- {
- if (!this.disposed)
- {
- if (disposing)
- {
- if (fs != null)
- fs.Close();
- }
- fs = null;
- disposed = true;
- }
- }
- }
- }
Excel导入到DataTable ,DataTable导入到Excel的更多相关文章
- 【C#常用方法】2.DataTable(或DataSet)与Excel文件之间的导出与导入(使用NPOI)
DataTable与Excel之间的互导 1.项目添加NPOI的引用 NPOI项目简介: NPOI是一个开源的C#读写Excel.WORD等微软OLE2组件文档的项目,特点是可以在没有安装Office ...
- .net实现与excel的数据交互、导入导出
应该说,一套成熟的基于web的管理系统,与用户做好的excel表格进行数据交互是一个不可或缺的功能,毕竟,一切以方便客(jin)户(qian)为宗旨. 本人之前从事PHP的开发工作,熟悉PHP的都应该 ...
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- Excel大数据量分段导入到Oracle
客户需要将一个具有2W多条数据的Excel表格中的数据导入到Oracle数据库的A表中,开始采用的是利用Oledb直接将数据读入到DataTable中,然后通过拼接InserInto语句来插入到数据库 ...
- C#调用NPOI组件读取excel表格数据转为datatable写入word表格中并向word中插入图片/文字/书签 获得书签列表
调用word的com组件将400条数据导入word表格中耗时10分钟简直不能忍受,使用NPOI组件耗时4秒钟.但是NPOI中替换书签内容的功能不知道是不支持还是没找到. 辅助类 Excel表格数据与D ...
- Excel导入导出,生成和下载Excel报表、附件等操作--ASP.NET
public class OutExcel { public static void OutExcel_bb(DataTable dt, string thepath, string temppath ...
- 使用OpenXML将Excel内容读取到DataTable中
前言:前面的几篇文章简单的介绍了如何使用OpenXML创建Excel文档.由于在平时的工作中需要经常使用到Excel的读写操作,简单的介绍下使用 OpenXML读取Excel中得数据.当然使用Open ...
- .Net之Nopi Excel数据导出和批量导入功能
一.介绍NPOI和编写demo的原因 1.Npoi是什么: 它是一个专门用于读写Microsoft Office二进制和OOXML文件格式的.NET库,我们使用它能够轻松的实现对应数据的导入,导出功能 ...
- DataTable数据导出到Excel,并发送到客户端进行下载
本代码实现思路是:页面显示和导出分开,导出的数据和用于页面显示的是同一查询数据方式,所以也是同样的数据,只是在导出数据时从数据库重新捞了一次数据.此导出数据方式会先将数据保存到Excel中,然后将创建 ...
- datatable导出到Word / Excel / PDF / HTML .NET
原文发布时间为:2011-01-21 -- 来源于本人的百度文章 [由搬家工具导入] IEnumerable - DataTable Export to Word / Excel / PDF / HT ...
随机推荐
- Angular 通过constant(name,value),value(name,value)创建服务
区别: constant()可以将已经存在的变量值注册为服务,并将其注入到应用的其他部分中,他的value可以是值,也可以是对象.通过他来配置数据,也就是说可以在config里注入,但是他是不可以修改 ...
- (转)基于MVC4+EasyUI的Web开发框架经验总结(4)--使用图表控件Highcharts
http://www.cnblogs.com/wuhuacong/p/3736564.html 在我们做各种应用的时候,我们可能都会使用到图表统计,以前接触过一些不同的图表控件,在无意中发现了图表控件 ...
- ios 编译版本 最低版本 运行版本 动态链接库
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) 运行环境判断: #if __IPHONE_OS_VERSION_ ...
- js商城倒计时
js将秒转换为几天几小时几分钟 1 var oldsecond=second = 60,minute=0,hour=0,day=0; minute = parseInt(second/60); //算 ...
- 【数据分析】算法+Echarts小练
''' 处理逻辑: 按number去处理 先遍历所有的number挨个去找有没有在列表里的,在列表里的拿出另外一个append 把number去除的列表 ''' li = [] with open(r ...
- 路飞学城Python-Day108
96-分页器1 批量插入的方式就不能用ORM的create()方式去做了,因为create就是对sql进行insert的操作,sql最好不要每次有一条数据就去进行插入,最好的方式就是插入一组数据 fr ...
- MySQL笔记5-----索引(覆盖索引等)
1.概念: 覆盖索引:(个人理解)就是包含所有查询记录的索引.当查询量过大时可以采用覆盖索引来进行查询,效率较高. 回表:建立覆盖索引就是避免回表,回表效率会很慢. select查询的字段只有索引列, ...
- Codeforces Round #468 (Div. 2, based on Technocup 2018 Final Round)A. Friends Meeting
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the ...
- Blender软件导出的obj数据格式文件内容解读
[cube.obj] # Blender v2.78 (sub 0) OBJ File: '' # www.blender.org mtllib cube.mtl #这里是引用了一个外部材质文件cub ...
- 洛谷P1427 小鱼的数字游戏
题目描述 小鱼最近被要求参加一个数字游戏,要求它把看到的一串数字(长度不一定,以0结束,最多不超过100个,数字不超过2^32-1),记住了然后反着念出来(表示结束的数字0就不要念出来了).这对小鱼的 ...