/// <summary>
/// 写入到Excel表格文件当中,导出数据
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public bool DataTableToExcel(DataTable dt, string DataFile)
{
bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
ISheet sheet = null;
ICell cell = null;
try
{
if (dt != null && dt.Rows.Count > 0)
{
workbook = new HSSFWorkbook();
string NowBOPName = this.CmbBOPName.Text.Trim();
sheet = workbook.CreateSheet(NowBOPName);//创建一个名称为Sheet0的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数 //把A0:C0合并为一个单元格 并赋值
ICell hbcell = sheet.CreateRow(0).CreateCell(0);
hbcell.SetCellValue(NowBOPName + "工序");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 2)); //设置样式 居中 字体
ICellStyle hbstyle = workbook.CreateCellStyle();
hbstyle.VerticalAlignment = VerticalAlignment.Center;
hbstyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
IFont hbfont = workbook.CreateFont();
hbfont.FontHeight = 15 * 20;
hbstyle.SetFont(hbfont);
hbcell.CellStyle = hbstyle; //设置列头
row = sheet.CreateRow(1);//excel第一行设为标题,第二行列头
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
} //设置每行每列的单元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 2);//excel第三行开始写入数据
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
using (fs = File.OpenWrite(DataFile))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
result = true;
}
}
return result;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return false;
}
}
   /// <summary>
/// 将excel导入到datatable
/// </summary>
/// <param name="filePath">excel路径</param>
/// <param name="isColumnName">第一行是否是列名</param>
/// <returns>返回datatable</returns>
public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
{
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = 0;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(fs); if (workbook != null)
{ sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(1);//第二行列名
int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列
if (isColumnName)
{
startRow = 2;//如果第一行是标题,第二行列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
dataTable.Columns.Add(column);
}
}
}
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + 1));
dataTable.Columns.Add(column);
}
} //填充行
for (int i = startRow; i <= rowCount; ++i)
{
row = sheet.GetRow(i);
if (row == null) continue; dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)//dataTable.Columns.Count
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
//CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j - row.FirstCellNum] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58)
dataRow[j - row.FirstCellNum] = cell.DateCellValue;
else
dataRow[j - row.FirstCellNum] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j - row.FirstCellNum] = cell.StringCellValue;
break;
case CellType.Formula:
//System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
//nfi.NumberDecimalDigits = 2;
//short format = cell.CellStyle.Format("{0:F2}", Convert.ToDouble(23, 5235);
dataRow[j - row.FirstCellNum] = ((float)cell.NumericCellValue);
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
return dataTable;
}
catch (Exception ex)
{ if (fs != null)
{
fs.Close();
}
return null;
}
}

最新文章

  1. CheungSSH国产自动化运维工具开源Web界面
  2. tp5 model 的数据自动完成
  3. Web高级征程:《大型网站技术架构》读书笔记系列
  4. RPC hessian简单案例
  5. 【BZOJ 2038】【2009 国家集训队】小Z的袜子(hose) 分块+莫队
  6. sphinx索引文件进一步说明——最好是结合lucene一起看,直觉告诉我二者本质无异
  7. #ifdef 的技巧用法
  8. Computer Science Courses &ndash; Yan Yan
  9. iOS只执行一次的方法
  10. &lt;转载&gt;linux下内存泄露查找、BUG调试
  11. 当xcode里点运行出现treating unicode character as whites
  12. How do I pull a native DOM element from a jQuery object? | jQuery Learning Center
  13. Spring Security(14)——权限鉴定基础
  14. Java设计模式之《代理模式》及应用场景
  15. 全新定义!免费开源ERP平台如何玩转工业互联网
  16. 记录 制作校园网登陆脚本 python编写 附源码
  17. 【ECMAScript5】ECMAScript5中有关数组的常用方法
  18. c++结构体的排序
  19. 1.开始学习ASP.NET MVC
  20. 如何重写hashCode()和equals()方法

热门文章

  1. Window10环境下,Stable Diffusion的本地部署与效果展示
  2. 自己动手从零写桌面操作系统GrapeOS系列教程——8.x86介绍
  3. form表单enctype扩展
  4. DevExpress gridControl 字体居住
  5. lg9018题解
  6. 淘宝sign算法和使用教程
  7. 流(stream)如何理解?
  8. KU060板卡设计资料原理图第636篇:基于FMC的KU060高性能 PCIe 载板
  9. 关于tensor2tensor与tensorflow版本冲突的解决方案
  10. linux挂载磁盘步骤