NPOI DataTable转Excel ,Excel转DataTable

DataTableToExcel:

 1  public static void dataTableToExcel(DataTable table, string fileName)
 2         {
 3             using (MemoryStream ms = new MemoryStream())
 4             {
 5
 6                 IWorkbook workbook = null;
 7
 8                 if (fileName.IndexOf(".xlsx") > 0)
 9                     workbook = new XSSFWorkbook();
10                 if (fileName.IndexOf(".xls") > 0)
11                     workbook = new HSSFWorkbook();
12                 ISheet sheet = workbook.CreateSheet();
13                 IRow headerRow = sheet.CreateRow(0);
14
15                 // handling header.
16                 foreach (DataColumn column in table.Columns)
17                     headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value
18
19                 // handling value.
20                 int rowIndex = 1;
21
22                 foreach (DataRow row in table.Rows)
23                 {
24                     IRow dataRow = sheet.CreateRow(rowIndex);
25
26                     foreach (DataColumn column in table.Columns)
27                     {
28                         dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
29                     }
30
31                     rowIndex++;
32                 }
33
34                 workbook.Write(ms);
35                 ms.Flush();
36
37                 using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
38                 {
39                     byte[] data = ms.ToArray();
40
41                     fs.Write(data, 0, data.Length);
42                     fs.Flush();
43
44                     data = null;
45                 }
46             }
47         }

ExcelToDataTable:

  1    public static DataTable ExcelToDataTable(string filePath, bool isColumnName,int sheetName)
  2         {
  3             DataTable dataTable = null;
  4             FileStream fs = null;
  5             DataColumn column = null;
  6             DataRow dataRow = null;
  7             IWorkbook workbook = null;
  8             ISheet sheet = null;
  9             IRow row = null;
 10             ICell cell = null;
 11             int startRow = 0;
 12             try
 13             {
 14                 using (fs = File.OpenRead(filePath))
 15                 {
 16                     // 2007版本
 17                     if (filePath.IndexOf(".xlsx") > 0)
 18                         workbook = new XSSFWorkbook(fs);
 19                     // 2003版本
 20                     else if (filePath.IndexOf(".xls") > 0)
 21                         workbook = new HSSFWorkbook(fs);
 22
 23                     if (workbook != null)
 24                     {
 25                         sheet = workbook.GetSheetAt(sheetName);//读取第一个sheet,当然也可以循环读取每个sheet
 26                         dataTable = new DataTable();
 27                         if (sheet != null)
 28                         {
 29                             int rowCount = sheet.LastRowNum;//总行数
 30                             if (rowCount > 0)
 31                             {
 32                                 IRow firstRow = sheet.GetRow(0);//第一行
 33                                 int cellCount = firstRow.LastCellNum;//列数
 34
 35                                 //构建datatable的列
 36                                 if (isColumnName)
 37                                 {
 38                                     startRow = 1;//如果第一行是列名,则从第二行开始读取
 39                                     for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
 40                                     {
 41                                         cell = firstRow.GetCell(i);
 42                                         if (cell != null)
 43                                         {
 44                                             if (cell.StringCellValue != null)
 45                                             {
 46                                                 column = new DataColumn(cell.StringCellValue);
 47                                                 dataTable.Columns.Add(column);
 48                                             }
 49                                         }
 50                                     }
 51                                 }
 52                                 else
 53                                 {
 54                                     for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
 55                                     {
 56                                         column = new DataColumn("column" + (i + 1));
 57                                         dataTable.Columns.Add(column);
 58                                     }
 59                                 }
 60
 61                                 //填充行
 62                                 for (int i = startRow; i <= rowCount; ++i)
 63                                 {
 64                                     row = sheet.GetRow(i);
 65                                     if (row == null) continue;
 66
 67                                     dataRow = dataTable.NewRow();
 68                                     for (int j = row.FirstCellNum; j < cellCount; ++j)
 69                                     {
 70                                         cell = row.GetCell(j);
 71                                         if (cell == null)
 72                                         {
 73                                             dataRow[j] = "";
 74                                         }
 75                                         else
 76                                         {
 77                                             //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
 78                                             switch (cell.CellType)
 79                                             {
 80                                                 case CellType.Blank:
 81                                                     dataRow[j] = "";
 82                                                     break;
 83                                                 case CellType.Numeric:
 84                                                     short format = cell.CellStyle.DataFormat;
 85                                                     //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
 86                                                     if (format == 14 || format == 31 || format == 57 || format == 58)
 87                                                         dataRow[j] = cell.DateCellValue;
 88                                                     else
 89                                                         dataRow[j] = cell.NumericCellValue;
 90                                                     break;
 91                                                 case CellType.String:
 92                                                     dataRow[j] = cell.StringCellValue;
 93                                                     break;
 94                                             }
 95                                         }
 96                                     }
 97                                     dataTable.Rows.Add(dataRow);
 98                                 }
 99                             }
100                         }
101                     }
102                 }
103                 return dataTable;
104             }
105             catch (Exception ex)
106             {
107                 Console.WriteLine("exception:" + ex.ToString());
108                 Console.ReadLine();
109                 if (fs != null)
110                 {
111                     fs.Close();
112                 }
113                 return null;
114             }
115         }
时间: 2024-08-29 06:30:09

NPOI DataTable转Excel ,Excel转DataTable的相关文章

带复杂表头合并单元格的HtmlTable转换成DataTable并导出Excel(转)

步骤: 一.前台JS取HtmlTable数据,根据设定的分隔符把数据拼接起来 <!--导出Excel--> <script type="text/javascript"> //导出Excel function exportExcel() { var data = ""; $("#divRptTable").find("table").find("tr").each(function

DataTable导出到Excel文件

调用方法: ExcelHelper.Export(dtTemp, "供应商App", DlgSave.FileName, "物料文档" , new string[10] { "MatterCode", "MatterName", "MatterType", "MainUnit", "TagModelName", "LotName", "F

读取指定路径的Excel内容到DataTable中

1 /// <summary> 2 /// 读取指定路径的Excel内容到DataTable中 3 /// </summary> 4 /// <param name="path"></param> 5 /// <returns></returns> 6 public DataTable ImportToDataSet(string path) 7 { 8 string strConn = "Provide

DataTable导出到Excel

static DataTable GetTable() { // // Here we create a DataTable with four columns. // DataTable table = new DataTable(); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patien

服务器不装Excel读取Excel并转换DataTable

原来是用OleDb.4.0组件读取Excel,但是放到服务器后 傻了,服务器没装Excel ,而且领导说不可以装 没办法,只好自己重新找下代码 在CodeProject找到一个开源的dll,一阵欢喜啊,虽然是winform项目,但是主要是用他的类库所以提取一下后 自己研究后重新封装了一个类,运行 耶! 完美支持 需要Dome的同学下载后去研究下吧 地址:http://download.csdn.net/detail/jine515073/7266371 本人用 Excel 97-2003 工作表

将DataTable导出为Excel文件的方法

 需求:前台点击某个按钮,在后台从数据库中获取某DataTable数据到处成Excel文件. 1.Asp按钮控件 两个按钮,分别调用两种导出Excel文件的后台方法. <%--第一种方法--%> <form id="form1" runat="server"> <div> <asp:Button runat="server" OnClick="Btn1_Click" ID="

.net excel 转换成datatable,创建文件夹

protected void Button9_Click(object sender, EventArgs e) { string path = ""; path = FileUpload3.PostedFile.FileName; if (path == "") { string jss = "<script language='javascript' type='text/javascript'> alert('先选择文件')</sc

把DataTable导出为Excel文件

今天项目里遇到了需要把DataTable导出为Excel的问题将解决方案记录在园子备忘 需要一些东西第三方的类库Aspose.Cells此处随意找个下载链接:http://www.cr173.com/soft/66096.html本人不保证该链接的合法性和有效性 说重点,上Demo public bool ExportAsExcel(string URI, DataSet ds) { Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();

【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable

OleDbDataAdapter方式: /// <summary> /// 读取excel的表格放到DataTable中 ---OleDbDataAdapter /// </summary> /// <param name="strSql"></param>        /// <param name="excelpath">excel路径</param> /// <returns>

C#向Excel传输数据——批量dataTable

导出报表,将程序中的list或者dataTable进行组织.然后通过特定的形式,显示到Excel或者word中,方便打印. 目前正在使用的方式,事先用报表设计工具,设置一个模板,然后导出报表的时候,读取模板,然后将模板中的数据进行替换.这也是最常用的一个方式. 我们公司,现在没有使用报表工具,使用的Excel. 使用Excel做报表模板,然后向Excel中写数据,进而达到一个导出报表的功能. 因为有大量的数据需要写入到Excel,标签只是一个标记. 这样就提供了两种写入Excel的方式: 方法一