using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System; public class ExcelHelp
{
public class x2003
{
#region Excel2003
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xls)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLS(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
ISheet sheet = hssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xls)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLS(DataTable dt, string file)
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet = hssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
hssfworkbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xls)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLS(HSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
#endregion
} public class x2007
{
#region Excel2007
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xlsx)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLSX(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
ISheet sheet = xssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xlsx)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLSX(DataTable dt, string file)
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
ISheet sheet = xssfworkbook.CreateSheet("sheet1"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
xssfworkbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLSX(XSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
#endregion
} public static DataTable GetDataTable(string filepath)
{
try
{
var dt = new DataTable("xls");
if (filepath.Last() == 's')
{
dt = x2003.ExcelToTableForXLS(filepath);
}
else
{
dt = x2007.ExcelToTableForXLSX(filepath);
}
return dt;
}
catch (Exception ex)
{
return null;
}
} /// <summary>
/// 将Excel文件中的数据读出到DataTable中
/// </summary>
/// <param name="file">文件路径</param>
/// <param name="sheetName">工作表名称</param>
/// <param name="columnTypeDic">列名与列类型字典</param>
/// <returns>DataTable</returns>
public static DataTable ImportToTable(string file, string sheetName = "", Dictionary<string, Type> columnTypeDic = null)
{
DataTable dt = null;
FileStream fs = null;
try
{
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
IWorkbook workbook = WorkbookFactory.Create(fs);
ISheet sheet = string.IsNullOrEmpty(sheetName) ? workbook.GetSheetAt() : workbook.GetSheet(sheetName);
if (sheet == null) return null;
dt = SheetToDataTable(sheet, columnTypeDic);
fs.Close();
return dt;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return dt;
}
}
/// <summary>
/// 将Excel文件中的数据读出到DataSet中
/// </summary>
/// <param name="file">Excel文件路径</param>
/// <param name="columnTypeDic">列名与列类型字典</param>
/// <returns>DataSet</returns>
public static DataSet ImportToDataSet(string file, Dictionary<string, Type> columnTypeDic = null)
{
DataSet ds = new DataSet();
FileStream fs = null;
try
{
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
IWorkbook workbook = WorkbookFactory.Create(fs);
int sheetCount = workbook.NumberOfSheets;
for (int i = ; i < sheetCount; i++)
{
ISheet sheet = workbook.GetSheetAt(i);
if (sheet == null) continue;
DataTable dt = SheetToDataTable(sheet, columnTypeDic);
ds.Tables.Add(dt);
}
fs.Close();
return ds;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return ds;
}
}
/// <summary>
/// 将Sheet中的数据读出到DataTable中
/// </summary>
/// <param name="sheet">ISheet</param>
/// <param name="columnTypeDic">列名与列类型字典</param>
/// <returns>DataTable</returns>
private static DataTable SheetToDataTable(ISheet sheet, Dictionary<string, Type> columnTypeDic)
{
DataTable dt = new DataTable(sheet.SheetName);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
if (header == null) return dt;
for (int i = ; i < header.LastCellNum; i++)
{
ICell cell = header.GetCell(i);
object obj = GetCellValue(cell);
string columnName = "";
if (obj == null || string.IsNullOrEmpty(obj.ToString()) || dt.Columns.Contains(obj.ToString()))
columnName = "Columns" + i;
else
columnName = obj.ToString();
if (obj != null && dt.Columns.Contains(obj.ToString()))
{
}
if (columnTypeDic != null && columnTypeDic.ContainsKey(columnName))
dt.Columns.Add(columnName, columnTypeDic[columnName]);
else
dt.Columns.Add(columnName);
} //数据
int firstRowNum = sheet.FirstRowNum;//耗时操作,只读一次,提升效率
int lastRowNum = sheet.LastRowNum;
for (int i = firstRowNum + ; i <= lastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
for (int j = ; j < header.LastCellNum; j++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
ICell cell = row.GetCell(j);
if (cell == null) continue;
dr[j] = GetCellValue(cell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
return dt;
}
/// <summary>
/// 获取单元格的值
/// </summary>
/// <param name="cell">ICell</param>
/// <returns>object</returns>
private static object GetCellValue(ICell cell)
{
if (cell == null)
return null;
try
{
CellType cellType = cell.CellType == CellType.Formula ? cell.CachedFormulaResultType : cell.CellType;
switch (cellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
{
return cell.DateCellValue;
}
else//其他数字类型
{
return cell.NumericCellValue;
}
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
default:
return null;
}
}
catch (Exception ex)
{
return null;
}
}
}

最新文章

  1. Odoo 二次开发教程(五)-新API的介绍与应用
  2. 通过一个模拟程序让你明白ASP.NET MVC是如何运行的
  3. 原生js-焦点图轮播
  4. C++ 复制控制之复制构造函数
  5. Linux学习笔记(16)shell基础之Bash变量
  6. thinkphp常用Config.php配置项
  7. SlickGrid example 3: 可编辑单元
  8. U盘
  9. leetcode&mdash;sqrt
  10. Scala中class和object的区别
  11. 【Linux搭建创建FTP服务器】---完美解决 - 费元星
  12. js实现原生选项卡
  13. 【oracle】ORA-02289: sequence does not exist
  14. elasticsearch中 refresh 和flush区别(转)
  15. jmeter之正则表达式
  16. centos7 安装zabbix
  17. 前端基础之jQuery操作标签
  18. ubuntu单独安装字体包
  19. Smallest Difference(暴力全排列)
  20. centos6 安装GitLab

热门文章

  1. Entity Framework Core导航属性加载问题
  2. git core.autocrlf配置 解决Windows和Linux(Mac)换行问题
  3. 幂率定律及绘制Power-law函数
  4. libxml2_ZC积累
  5. [osg][osgEarth][osgGA][原] EarthManipulator------基于oe的相机漫游器(浅析)
  6. C#发起HTTP请求
  7. LeetCode第[20]题(Java):Valid Parentheses
  8. boke例子:用户登录
  9. Postman发包form-data、x-www-form-urlencoded、raw、binary的区别
  10. 基于VMware模拟实现远程主机网络通信