题外拓展:把datatable插入dataset

DataTable fuben = new DataTable();//定义的datatable
fuben = table.Tables[0].Copy(); 把获取的datatable复制到新的表中
fuben.TableName = "sheet" + userid + "";定义表名
ds.Tables.Add(fuben);插入dataset

之所以这么麻烦是因为 我用了返回dataset的方法来获取的datatable,导致提示此datatable已经属于另外一个dataset,所以只有把他复制到另外一个表,然后在插入dataset

我就直接把类复制进来了

调用的时候

参数ds为你定义的DataSet

ExcelRender.RenderToExcel(ds, Context, "报表.xls");

using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel; /// <summary>
/// 使用NPOI操作Excel,无需Office COM组件
/// Created By 囧月 http://lwme.cnblogs.com
/// 部分代码取自http://msdn.microsoft.com/zh-tw/ee818993.aspx
/// NPOI是POI的.NET移植版本,目前稳定版本中仅支持对xls文件(Excel 97-2003)文件格式的读写
/// NPOI官方网站http://npoi.codeplex.com/
/// </summary>
public class ExcelRender
{
/// <summary>
/// 根据Excel列类型获取列的值
/// </summary>
/// <param name="cell">Excel列</param>
/// <returns></returns>
private static string GetCellValue(ICell cell)
{
if (cell == null)
return string.Empty;
switch (cell.CellType)
{
case CellType.BLANK:
return string.Empty;
case CellType.BOOLEAN:
return cell.BooleanCellValue.ToString();
case CellType.ERROR:
return cell.ErrorCellValue.ToString();
case CellType.NUMERIC:
case CellType.Unknown:
default:
return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
case CellType.STRING:
return cell.StringCellValue;
case CellType.FORMULA:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
} /// <summary>
/// 自动设置Excel列宽
/// </summary>
/// <param name="sheet">Excel表</param>
private static void AutoSizeColumns(ISheet sheet)
{
if (sheet.PhysicalNumberOfRows > )
{
IRow headerRow = sheet.GetRow(); for (int i = , l = headerRow.LastCellNum; i < l; i++)
{
sheet.AutoSizeColumn(i);
}
}
} /// <summary>
/// 保存Excel文档流到文件
/// </summary>
/// <param name="ms">Excel文档流</param>
/// <param name="fileName">文件名</param>
private static void SaveToFile(MemoryStream ms, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray(); fs.Write(data, , data.Length);
fs.Flush(); data = null;
}
} /// <summary>
/// 输出文件到浏览器
/// </summary>
/// <param name="ms">Excel文档流</param>
/// <param name="context">HTTP上下文</param>
/// <param name="fileName">文件名</param>
private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
{
if (context.Request.Browser.Browser == "IE")
fileName = HttpUtility.UrlEncode(fileName);
context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
context.Response.BinaryWrite(ms.ToArray());
} /// <summary>
/// DataReader转换成Excel文档流
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static MemoryStream RenderToExcel(IDataReader reader)
{
MemoryStream ms = new MemoryStream(); using (reader)
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(); IRow headerRow = sheet.CreateRow();
int cellCount = reader.FieldCount; // handling header.
for (int i = ; i < cellCount; i++)
{
headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
} // handling value.
int rowIndex = ;
while (reader.Read())
{
IRow dataRow = sheet.CreateRow(rowIndex); for (int i = ; i < cellCount; i++)
{
dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
} rowIndex++;
} AutoSizeColumns(sheet); workbook.Write(ms);
ms.Flush();
ms.Position = ; }
return ms;
} /// <summary>
/// DataReader转换成Excel文档流,并保存到文件
/// </summary>
/// <param name="reader"></param>
/// <param name="fileName">保存的路径</param>
public static void RenderToExcel(IDataReader reader, string fileName)
{
using (MemoryStream ms = RenderToExcel(reader))
{
SaveToFile(ms, fileName);
}
} /// <summary>
/// DataReader转换成Excel文档流,并输出到客户端
/// </summary>
/// <param name="reader"></param>
/// <param name="context">HTTP上下文</param>
/// <param name="fileName">输出的文件名</param>
public static void RenderToExcel(IDataReader reader, HttpContext context, string fileName)
{
using (MemoryStream ms = RenderToExcel(reader))
{
RenderToBrowser(ms, context, fileName);
}
} /// <summary>
/// DataTable转换成Excel文档流
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static MemoryStream RenderToExcel(DataTable table)
{
MemoryStream ms = new MemoryStream(); using (table)
{
IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("sheet1"); IRow headerRow = sheet.CreateRow(); // handling header.
foreach (DataColumn column in table.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value // handling value.
int rowIndex = ; foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
} rowIndex++;
}
AutoSizeColumns(sheet); workbook.Write(ms);
ms.Flush();
ms.Position = ; }
return ms;
} /// <summary>
/// DataSet转换成Excel文档流
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static MemoryStream RenderToExcel(DataSet ds)
{
MemoryStream ms = new MemoryStream();
IWorkbook workbook = new HSSFWorkbook();
for (int i = ; i < ds.Tables.Count; i++)
{
DataTable table = ds.Tables[i];
ISheet sheet = workbook.CreateSheet(table.TableName); IRow headerRow = sheet.CreateRow(); // handling header.
foreach (DataColumn column in table.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value // handling value.
int rowIndex = ; foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
} rowIndex++;
}
AutoSizeColumns(sheet); workbook.Write(ms);
ms.Flush();
ms.Position = ; }
return ms;
}
/// <summary>
/// DataTable转换成Excel文档流,并保存到文件
/// </summary>
/// <param name="table"></param>
/// <param name="fileName">保存的路径</param>
public static void RenderToExcel(DataTable table, string fileName)
{
using (MemoryStream ms = RenderToExcel(table))
{
SaveToFile(ms, fileName);
}
} /// <summary>
/// DataTable转换成Excel文档流,并输出到客户端
/// </summary>
/// <param name="table"></param>
/// <param name="response"></param>
/// <param name="fileName">输出的文件名</param>
public static void RenderToExcel(DataTable table, HttpContext context, string fileName)
{
using (MemoryStream ms = RenderToExcel(table))
{
RenderToBrowser(ms, context, fileName);
}
} /// <summary>
/// DataSet转换成Excel文档流,并输出到客户端
/// </summary>
/// <param name="table"></param>
/// <param name="response"></param>
/// <param name="fileName">输出的文件名</param>
public static void RenderToExcel(DataSet ds, HttpContext context, string fileName)
{
using (MemoryStream ms = RenderToExcel(ds))
{
RenderToBrowser(ms, context, fileName);
}
}
/// <summary>
/// Excel文档流是否有数据
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <returns></returns>
public static bool HasData(Stream excelFileStream)
{
return HasData(excelFileStream, );
} /// <summary>
/// Excel文档流是否有数据
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetIndex">表索引号,如第一个表为0</param>
/// <returns></returns>
public static bool HasData(Stream excelFileStream, int sheetIndex)
{
using (excelFileStream)
{
IWorkbook workbook = new HSSFWorkbook(excelFileStream); if (workbook.NumberOfSheets > )
{
if (sheetIndex < workbook.NumberOfSheets)
{
ISheet sheet = workbook.GetSheetAt(sheetIndex); return sheet.PhysicalNumberOfRows > ; }
} }
return false;
} /// <summary>
/// Excel文档流转换成DataTable
/// 第一行必须为标题行
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetName">表名称</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName)
{
return RenderFromExcel(excelFileStream, sheetName, );
} /// <summary>
/// Excel文档流转换成DataTable
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetName">表名称</param>
/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
{
DataTable table = null; using (excelFileStream)
{
IWorkbook workbook = new HSSFWorkbook(excelFileStream);
{
ISheet sheet = workbook.GetSheet(sheetName); table = RenderFromExcel(sheet, headerRowIndex); }
}
return table;
} /// <summary>
/// Excel文档流转换成DataTable
/// 默认转换Excel的第一个表
/// 第一行必须为标题行
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream)
{
return RenderFromExcel(excelFileStream, , );
} /// <summary>
/// Excel文档流转换成DataTable
/// 第一行必须为标题行
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetIndex">表索引号,如第一个表为0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex)
{
return RenderFromExcel(excelFileStream, sheetIndex, );
} /// <summary>
/// Excel文档流转换成DataTable
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetIndex">表索引号,如第一个表为0</param>
/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
{
DataTable table = null; using (excelFileStream)
{
IWorkbook workbook = new HSSFWorkbook(excelFileStream); ISheet sheet = workbook.GetSheetAt(sheetIndex); table = RenderFromExcel(sheet, headerRowIndex); }
return table;
} /// <summary>
/// Excel表格转换成DataTable
/// </summary>
/// <param name="sheet">表格</param>
/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
/// <returns></returns>
private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)
{
DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(headerRowIndex);
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1 //handling header.
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
} for (int i = (sheet.FirstRowNum + ); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow(); if (row != null)
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = GetCellValue(row.GetCell(j));
}
} table.Rows.Add(dataRow);
} return table;
} /// <summary>
/// Excel文档导入到数据库
/// 默认取Excel的第一个表
/// 第一行必须为标题行
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="insertSql">插入语句</param>
/// <param name="dbAction">更新到数据库的方法</param>
/// <returns></returns>
public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction)
{
return RenderToDb(excelFileStream, insertSql, dbAction, , );
} public delegate int DBAction(string sql, params IDataParameter[] parameters); /// <summary>
/// Excel文档导入到数据库
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="insertSql">插入语句</param>
/// <param name="dbAction">更新到数据库的方法</param>
/// <param name="sheetIndex">表索引号,如第一个表为0</param>
/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
/// <returns></returns>
public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction, int sheetIndex, int headerRowIndex)
{
int rowAffected = ;
using (excelFileStream)
{
IWorkbook workbook = new HSSFWorkbook(excelFileStream); ISheet sheet = workbook.GetSheetAt(sheetIndex); StringBuilder builder = new StringBuilder(); IRow headerRow = sheet.GetRow(headerRowIndex);
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1 for (int i = (sheet.FirstRowNum + ); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
if (row != null)
{
builder.Append(insertSql);
builder.Append(" values (");
for (int j = row.FirstCellNum; j < cellCount; j++) {
builder.AppendFormat("'{0}',", GetCellValue(row.GetCell(j)).Replace("'", "''"));
}
builder.Length = builder.Length - ;
builder.Append(");");
} if ((i % == || i == rowCount) && builder.Length > )
{
//每50条记录一次批量插入到数据库
rowAffected += dbAction(builder.ToString());
builder.Length = ;
}
} }
return rowAffected;
}
}

利用npoi把多个DataTable导入Excel多个sheet中的更多相关文章

  1. .net导入excel数据到数据库中

    在开发过程中我们经常面临着需要将数据导出或者导入到系统中,例如一些生产管理系统,项目管理系统等等都会有这样的需求: 将excel数据到系统中思路:获取excel中每一行的数据,然后存入集合中,批量添加 ...

  2. NPOI 2.1.3.1导入Excel

    引入NPOI 2.1.3.1的包 项目引入 using NPOI.XSSF.UserModel;using NPOI.SS.UserModel; 控制器方法: public ActionResult ...

  3. Winform .NET 利用NPOI导出大数据量的Excel

    前言:公司让做一个导出数据到Excel的小工具,要求是用户前端输入sql语句,点击导出按钮之后,将数据导出到Excel,界面如图所示:文件下端显示导出的进度 遇到的问题: 1.使用NPOI进行Exce ...

  4. NCUAP 利用java自带方法实现导入excel取数据

    final JComponent parent = getModel().getContext().getEntranceUI(); JFileChooser chooser = new JFileC ...

  5. asp.net 导入Excel记录到数据库中

    常用到的一个数据库导入功能,这样的话就省了很大一部分时间来处理程序上的问题而不是无休止的重复复制粘贴动作. 其他的废话不多说,直接上代码: 前提条件: 根目录下建立uploadfiles文件夹(用于保 ...

  6. MYSQL 导入Excel数据到数据库中

    1,先把excel的数据整理整齐,如每列都要保持同样的格式:就一列一列的数据: 2,导出excel的数据为CSV格式,即把excel的数据另存为xxxx.csv;: 3,用EditPlus工具将xxx ...

  7. .net上传文件,利用npoi读取文件信息到datatable里

    整理代码,.net上传文件,利用npoi读取文件到datatable里,使用了FileUpload控件,代码如下: protected void Button1_Click(object sender ...

  8. [Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你!

    引言 项目中常用到将数据导入Excel,将Excel中的数据导入数据库的功能,曾经也查找过相关的内容,将曾经用过的方案总结一下. 方案一 NPOI NPOI 是 POI 项目的 .NET 版本.POI ...

  9. 转:[Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你!

    引言 项目中常用到将数据导入Excel,将Excel中的数据导入数据库的功能,曾经也查找过相关的内容,将曾经用过的方案总结一下. 方案一 NPOI NPOI 是 POI 项目的 .NET 版本.POI ...

随机推荐

  1. js--事件对象的理解4

    阻止默认行为:1.实例-简易修改右键菜单<script>document.oncontextmenu=function (ev){ var oEvent=ev||event; var oU ...

  2. qt 汉化 国际化

    两种方法. 1. 使用 QTextCodec  setcodeforname 设置编码, 然后在程序中对于需要处理的字符使用 fromLocal8Bit . 2. 使用 Linguist. 首先把文件 ...

  3. ckplayer 实现

    <div id="flashcontent"></div> <div id="video" style="positio ...

  4. C语言实现用户输入

    用户输入一个字符串然后回车表示结束.因为用户在输入的过程中长度是不确定的,所以要求自己使用的循环写的更好.在这里自己写了一个代码,效率不高,相对来说如果能模拟出C++中的vector向量可能会好一些. ...

  5. Twitter Storm源代码分析之Nimbus/Supervisor本地目录结构

    storm集群里面工作机器分为两种一种是nimbus, 一种是supervisor, 他们通过zookeeper来进行交互,nimbus通过zookeeper来发布一些指令,supervisor去读z ...

  6. LeetCode OJ 33. Search in Rotated Sorted Array

    Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ...

  7. chapter 12_1 数据文件

    Lua的一个重要特性,就是可以作为配置文件,利用到table构造式来定义一种文件格式. 只需要在写数据时做一点额外的工作,读取数据就会变得相当容易.也就是将数据作为Lua代码输出. 当运行这些代码时, ...

  8. Mainline/Stable/Legacy

    Nginx官网提供了三个类型的版本Mainline version:Mainline 是 Nginx 目前主力在做的版本,可以说是开发版Stable version:最新稳定版,生产环境上建议使用的版 ...

  9. I Think I Need a Houseboat

    I Think I Need a Houseboat Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java ...

  10. 711B - Chris and Magic Square 模拟

    题目大意:在num[i][j]==0处填一个数使每行,每列,对角线的和相同,若果有多种答案输出一种. 题目思路:模拟 #include<iostream> #include<algo ...