using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI;
using NPOI.OpenXml4Net.OPC;
using System.Data; namespace TransactionToString
{
public class OperationExcel
{
private int insertRowIndex;
private int insertRowCount;
private Dictionary<int, string> insertData;
private IWorkbook workbook; public OperationExcel(int insertRowIndex, int insertRowCount,Dictionary<int,string> insertData=null)
{
if (insertData!=null)
{
this.insertData = insertData;
}
this.insertRowIndex = insertRowIndex;
this.insertRowCount = insertRowCount;
} public OperationExcel()
{ }
private IWorkbook NPOIOpenExcel(string filename)
{
IWorkbook myworkBook;
Stream excelStream = OpenResource(filename);
if (POIFSFileSystem.HasPOIFSHeader(excelStream))
return new HSSFWorkbook(excelStream);
if (POIXMLDocument.HasOOXMLHeader(excelStream))
{
return new XSSFWorkbook(OPCPackage.Open(excelStream));
}
if (filename.EndsWith(".xlsx"))
{
return new XSSFWorkbook(excelStream);
}
if (filename.EndsWith(".xls"))
{
new HSSFWorkbook(excelStream);
}
throw new Exception("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
} private Stream OpenResource(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
return fs;
} private void InsertRow(ISheet sheet,int insertRowIndex,int insertRowCount,IRow formatRow)
{
ICellStyle styleText= sheet.Workbook.CreateCellStyle();
IDataFormat dataformat = sheet.Workbook.CreateDataFormat();
styleText.DataFormat = dataformat.GetFormat("@");
sheet.ShiftRows(insertRowIndex, sheet.LastRowNum, insertRowCount, true, false);
for (int i = insertRowIndex; i < insertRowIndex+insertRowCount; i++)
{
IRow targetRow = null;
ICell sourceCell = null;
ICell targetCell = null;
targetRow = sheet.CreateRow(i);
for (int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++)
{
sourceCell = formatRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (sourceCell==null)
{
continue;
}
targetCell = targetRow.CreateCell(m);
}
} for (int i = insertRowIndex; i < insertRowIndex + insertRowCount; i++)
{
IRow firstTargetRow = sheet.GetRow(i);
ICell firstSourceCell = null;
ICell firstTargetCell = null; for (int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++)
{
firstSourceCell = formatRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (firstSourceCell == null)
{
continue;
}
firstTargetCell = firstTargetRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (this.insertData!=null&&this.insertData.Count>)
{
firstTargetCell.SetCellValue(insertData[m]);
}
firstTargetCell.SetCellValue("test");
}
} } public void WriteToFile(IWorkbook workbook,string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (FileStream fs=new FileStream(filename,FileMode.OpenOrCreate,FileAccess.Write))
{
workbook.Write(fs);
fs.Close();
}
} public void OpenExcel(string filename)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = filename;
process.StartInfo.ErrorDialog = true;
process.Start();
} public void EditorExcel(string savePath, string readPath, OperationExcel oe)
{
try
{
IWorkbook workbook = oe.NPOIOpenExcel(readPath);
if (workbook == null)
{
return;
}
int sheetNum = workbook.NumberOfSheets;
for (int i = ; i < sheetNum; i++)
{
ISheet mysheet = workbook.GetSheetAt(i);
IRow mySourceRow = mysheet.GetRow(insertRowIndex);
oe.InsertRow(mysheet, insertRowIndex, insertRowCount, mySourceRow); } oe.WriteToFile(workbook, savePath);
oe.OpenExcel(savePath);
}
catch (Exception ex)
{ throw new Exception(ex.Message);
} } public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten,string fileName)
{
int i = ;
int j = ;
int count = ;
ISheet sheet = null;
if (File.Exists(fileName))
File.Delete(fileName);
var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > )
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > )
workbook = new HSSFWorkbook(); try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -;
} if (isColumnWritten == true)
{
IRow row = sheet.CreateRow();
for (j = ; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = ;
}
else
{
count = ;
} for (i = ; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = ; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs);
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -;
}
} public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn,string fileName)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = ;
try
{
var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > )
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > )
workbook = new HSSFWorkbook(fs); if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null)
{
sheet = workbook.GetSheetAt();
}
}
else
{
sheet = workbook.GetSheetAt();
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow();
int cellCount = firstRow.LastCellNum; 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 + ;
}
else
{
startRow = sheet.FirstRowNum;
} int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;      DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
}
}

NPOI 将excel转换为datatable或者将datatable转换为excel的更多相关文章

  1. excel to datatable (c#用NPOI将excel文件内容读取到datatable数据表中)

    将excel文件内容读取到datatable数据表中,支持97-2003和2007两种版本的excel 1.第一种是根据excel文件路径读取excel并返回datatable /// <sum ...

  2. 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    using System; using System.Collections.Generic; using System.Text; using System.IO; using NPOI.SS.Us ...

  3. winfrom 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    1.通过NUGET管理器下载nopi,在引入命令空间 using System; using System.Collections.Generic; using System.Text; using ...

  4. .net读取Excel转datatable、.net读取的Excel存在合并单元格并且转成datatable

    项目中经常会遇到Excel导入数据,Excel的模板会可能是存在合并单元格的,模板如下图所示 读取时需要填充合并单元格的值,转成datatable单元格值时,填充合并单元格的值,如下图所示: 合并单元 ...

  5. DataTable转换为List<T>或者DataRow转换为T

    这段时间开发ASP.NETMVC应用程序,从数据库获取数据之后,需要把记录转换为数据集在视图中显示.我们需要把DataTable转换为List<T>或者DataRow转换为T. 本篇中可以 ...

  6. Excel导入导出,通过datatable转存(篇一)

    //导入数据 public ActionResult ExpressInfoImport() { var ptcp = new BaseResponse() { DoFlag = true, DoRe ...

  7. c#常用的Datable转换为json,以及json转换为DataTable操作方法

    #region  DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...

  8. “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用

    “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用 造成这个错误的原因是,在 ...

  9. .net 打开Excel文档并转为DataTable

    /// <summary> /// 打开Excel文档并转为DataTable /// </summary> /// <returns></returns&g ...

随机推荐

  1. LC 981. Time Based Key-Value Store

    Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, s ...

  2. leetcode 96. Unique Binary Search Trees 、95. Unique Binary Search Trees II 、241. Different Ways to Add Parentheses

    96. Unique Binary Search Trees https://www.cnblogs.com/grandyang/p/4299608.html 3由dp[1]*dp[1].dp[0]* ...

  3. Build Telemetry for Distributed Services之OpenTracing实践

    官网:https://opentracing.io/docs/best-practices/ Best Practices This page aims to illustrate common us ...

  4. 阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_05-新增页面-服务端-接口测试

    其从程序swaggerUI测试 pageName和别名都是 test003 { "dataUrl": "string", "htmlFileId&qu ...

  5. SpringBoot学习之一 Unable to find a single main class from the following candidates

    在启动SpringBoot项目是报错 Unable to find a single main class from the following candidates [boot.myboot.Sam ...

  6. hadoop异常: java.io.EOFException: Unexpected end of input stream

    执行hadoop任务时报错: -- ::, INFO [main] org.apache.hadoop.mapred.MapTask: Processing --//app1@flume23_1000 ...

  7. 学用 ASP.Net 之 System.Collections.ArrayList 类

    ArrayList 是 .Net 的动态数组. 主要成员: /* 静态方法 */ ArrayList.Adapter() //把其他 IList 对象包装为 ArrayList 使用 ArrayLis ...

  8. Oracle GoldenGate OGG管理员手册

    第一章 系统实现简述 前言 编写本手册的目的是为系统管理员以及相关操作人员提供 Oracle  Goldengat  软 件的日常维护和使用的技术参考: 3 ORACLE 第二章 OGG 日常维护操作 ...

  9. FPGA回忆记事(一):基于Nios II的LED实验

    实验一:基于Nios II的LED实验 一.    创建Quartus II工程 1.打开Quartus II环境.开始->程序->Altera->Quartus II 9.1. 2 ...

  10. webdriervAPI(控制浏览器及简单元素操作)

    from  selenium  import  webdriver driver  =  webdriver.Chorme() driver.get("http://www.baidu.co ...