NPOI Helper文档
public class ExcelHelper
{
/// <summary>
/// NPOI Excel转DataTable
/// </summary>
/// <param name="excelServerPath"></param>
/// <returns></returns>
public static DataTable ExcelToDataTable(string excelServerPath, bool hasTitle = true)
{
FileStream fs = System.IO.File.OpenRead(excelServerPath);
IWorkbook workBook = WorkbookFactory.Create(fs, ImportOption.All); ISheet sheet = workBook.GetSheetAt();
DataTable dt = null;
if (hasTitle)
{
dt = SheetToDataTableHasTitle(sheet);
}
else
{
dt = SheetToDataTable(sheet);
}
fs.Close();
fs.Dispose();
workBook.Close();
return dt;
} /// <summary>
/// NPOI Excel转DataTable
/// </summary>
/// <param name="excelServerPath"></param>
/// <returns></returns>
public static DataTable ExcelToDataTable(Stream stream)
{
IWorkbook workBook = WorkbookFactory.Create(stream, ImportOption.All); ISheet sheet = workBook.GetSheetAt();
DataTable dt = SheetToDataTable(sheet); workBook.Close();
return dt;
} /// <summary>
/// NPOI Excel转DataSet
/// </summary>
/// <param name="excelServerPath"></param>
/// <returns></returns>
public static DataSet ExcelToDataSet(string excelServerPath, bool hasTitle = true)
{
FileStream fs = System.IO.File.OpenRead(excelServerPath);
IWorkbook workBook = WorkbookFactory.Create(fs, ImportOption.All);
fs.Close();
fs.Dispose(); DataSet ds = new DataSet();
for (int i = ; i < workBook.NumberOfSheets; i++)
{
ISheet sheet = workBook.GetSheetAt(i);
DataTable dt = null;
if (hasTitle)
{
dt = SheetToDataTableHasTitle(sheet);
}
else
{
dt = SheetToDataTable(sheet);
}
ds.Tables.Add(dt);
}
return ds;
} /// <summary>
/// NPOI DataTable转Excel
/// </summary>
/// <param name="dt"></param>
/// <param name="fileName"></param>
/// <param name="contentEncode"></param>
public static void Export(DataTable dt, string fileName, Dictionary<int, List<string>> dic = null)
{
if (dt == null || dt.Columns.Count <= )
{
return;
}
IWorkbook workBook = new HSSFWorkbook();
DataTableFillWorkBook(dt, workBook, dic);
Export(workBook, fileName);
} /// <summary>
/// NPOI DataSet转Excel
/// </summary>
public static void Export(DataSet ds, string fileName, Dictionary<int, Dictionary<int, List<string>>> dic = null)
{
if (ds == null || ds.Tables.Count <= )
{
return;
}
IWorkbook workBook = new HSSFWorkbook();
for (int i = ; i < ds.Tables.Count; i++)
{
var dt = ds.Tables[i];
Dictionary<int, List<string>> itemDic = null;
if (dic != null && dic.ContainsKey(i))
{
itemDic = dic[i];
}
DataTableFillWorkBook(dt, workBook, itemDic);
}
Export(workBook, fileName);
} /// <summary>
/// 根据DataTable导出csv文件
/// </summary>
/// <param name="dataTable">DataTable数据</param>
/// <param name="fileName">文件名(不带后缀)</param>
/// <param name="encodeName">编码方式 如 utf-8</param>
/// <param name="isCloseHttpResponse">是否关闭HttpResponse</param>
public static void ExportCsv(DataTable dataTable, string fileName, string encodeName, bool isCloseHttpResponse)
{
HttpResponse httpResponse = HttpContext.Current.Response; if (null == dataTable)
{
return;
} StringBuilder strBuilder = new StringBuilder(); //组合信息
int columnCount = dataTable.Columns.Count; for (int i = ; i < columnCount; i++)
{
string colName = dataTable.Columns[i].ColumnName + "";
if (colName.Contains(","))
{
colName = colName.Replace(",", ",");
} if (i == columnCount - )
{
strBuilder.Append(colName + "\r\n");
}
else
{
strBuilder.Append(colName + ",");
}
} foreach (DataRow row in dataTable.Rows)
{
for (int i = ; i < columnCount; i++)
{
string rowValue = row[i].ToString() + "";
if (rowValue.Contains(","))
{
rowValue = rowValue.Replace(",", ",");
} //如果是行尾
if (i == columnCount - )
{
strBuilder.Append(rowValue + "\r\n");
}
else
{
strBuilder.Append(rowValue + ",");
}
}
} #region 客户端导出文件 //内容编码格式设定
Encoding contentEncode = Encoding.GetEncoding(encodeName);
httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".csv");
httpResponse.ContentEncoding = contentEncode;
httpResponse.ContentType = ".csv"; httpResponse.Clear();
httpResponse.Write(strBuilder.ToString());
httpResponse.End(); #endregion
} /// <summary>
/// 根据DataTable导出csv文件
/// </summary>
/// <param name="csvServerPath">csv路径</param>
public static DataTable CsvToDataTable(string csvServerPath)
{
Regex reg = new Regex("\",\""); int intColCount = ;
DataTable dt = new DataTable("myTableName"); string columnLine;
string[] columnsArray; using (StreamReader streamReader = new StreamReader(csvServerPath, System.Text.Encoding.Default))
{
columnLine = streamReader.ReadLine();
columnsArray = columnLine.Split(','); intColCount = columnsArray.Length;
for (int i = ; i < columnsArray.Length; i++)
{
DataColumn mydc = new DataColumn(columnsArray[i].Replace("\"", ""), typeof(string));
dt.Columns.Add(mydc);
} while ((columnLine = streamReader.ReadLine()) != null)
{
columnsArray = columnLine.Split(','); DataRow mydr = dt.NewRow();
for (int i = ; i < intColCount; i++)
{
mydr[i] = columnsArray[i].Replace("\"", "");
} dt.Rows.Add(mydr);
}
} return dt;
} /// <summary>
/// 导出EXCEL
/// </summary>
/// <param name="strContent">html</param>
/// <param name="fileName"></param>
/// <param name="contentEncode"></param>
public static void HtmlExcel(string strContent, string fileName, Encoding contentEncode)
{
ExportExcel(strContent, fileName, contentEncode);
} /// <summary>
/// 导出Excel
/// </summary>
/// <param name="strContent">内容</param>
/// <param name="fileName">文件名称</param>
/// <param name="contentEncode">内容编码</param>
private static void ExportExcel(string strContent, string fileName, Encoding contentEncode)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
strBuilder.Append("<head>");
strBuilder.Append("<xml>");
strBuilder.Append("<x:ExcelWorkbook>");
strBuilder.Append("<x:ExcelWorksheets>");
strBuilder.Append("<x:ExcelWorksheet>");
strBuilder.Append("<x:Name>Sheet1</x:Name>");
strBuilder.Append("<x:WorksheetOptions>");
strBuilder.Append("<x:Print>");
strBuilder.Append("<x:ValidPrinterInfo/>");
strBuilder.Append("</x:Print>");
strBuilder.Append("</x:WorksheetOptions>");
strBuilder.Append("</x:ExcelWorksheet>");
strBuilder.Append("</x:ExcelWorksheets>");
strBuilder.Append("</x:ExcelWorkbook>");
strBuilder.Append("</xml>");
strBuilder.Append("</head>");
strBuilder.Append("<body><table>");
strBuilder.Append(strContent);
strBuilder.Append("</table></body>");
strBuilder.Append("</html>"); #region 客户端导出文件 HttpResponse httpResponse = HttpContext.Current.Response; httpResponse.AddHeader("Pragma", "public");
httpResponse.AddHeader("Cache-Control", "max-age=0");
httpResponse.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
httpResponse.ContentEncoding = contentEncode;
httpResponse.ContentType = "application/vnd.ms-excel"; httpResponse.Clear();
httpResponse.Write(strBuilder.ToString());
httpResponse.End(); #endregion
} /// <summary>
/// 输出Excel
/// </summary>
/// <param name="workBook"></param>
/// <param name="fileName"></param>
/// <param name="contentEncode"></param>
public static void Export(IWorkbook workBook, string fileName)
{
MemoryStream ms = new MemoryStream();
workBook.Write(ms);
HttpResponse httpResponse = HttpContext.Current.Response;
httpResponse.AddHeader("Pragma", "public");
httpResponse.AddHeader("Cache-Control", "max-age=0");
String userAgent = HttpContext.Current.Request.UserAgent;
//IE
if (userAgent.ToUpper().IndexOf("MSIE") > )
{
fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
}
httpResponse.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
//httpResponse.AddHeader("content-type", "application/x-msdownload");
//httpResponse.ContentEncoding = Encoding.UTF8;
httpResponse.ContentType = "application/vnd.ms-excel";
httpResponse.BinaryWrite(ms.ToArray());
workBook = null;
ms.Close();
ms.Dispose();
} /// <summary>
/// 构造Excel下拉
/// </summary>
/// <param name="sheet"></param>
/// <param name="dic"></param>
public static void StructWorkbookDropdown(ISheet sheet, Dictionary<int, List<string>> dic = null)
{
foreach (var item in dic.Keys)
{
if (dic[item] != null && dic[item].Count > )
{
CellRangeAddressList regions = new CellRangeAddressList(, , item, item);
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(dic[item].ToArray());
HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
sheet.AddValidationData(dataValidate);
}
}
} /// <summary>
/// 清空单元格内容
/// </summary>
public static void RemoveSheetContent(ISheet sheet, bool isRemoveRow, CellRangeAddress address)
{
for (int i = address.FirstRow; i <= address.LastRow; i++)
{
//移除全部合并
for (int n = sheet.NumMergedRegions - ; n >= ; n--)
{
sheet.RemoveMergedRegion(n);
} IRow row = sheet.GetRow(i);
if (row == null)
{
continue;
}
if (isRemoveRow == true)
{
sheet.RemoveRow(row);
continue;
}
for (int c = address.FirstColumn; c <= address.LastColumn; c++)
{
ICell cell = row.GetCell(c);
if (cell == null)
{
continue;
}
cell.SetCellValue("");
}
}
} #region 私有方法 /// <summary>
/// NPOI Sheet转Datatable
/// </summary>
/// <param name="sheet"></param>
/// <returns></returns>
private static DataTable SheetToDataTable(ISheet sheet)
{
if (sheet.LastRowNum <= )
{
return null;
} DataTable dt = new DataTable(sheet.SheetName); int maxColumnCount = ;
for (int i = ; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null || row.LastCellNum <= maxColumnCount)
{
continue;
}
maxColumnCount = row.LastCellNum;
} for (int i = ; i < maxColumnCount; i++)
{
dt.Columns.Add();
} for (int i = ; i <= sheet.LastRowNum; i++)
{
DataRow dataRow = dt.NewRow();
IRow row = sheet.GetRow(i);
if (row == null)
{
continue;
}
for (int j = ; j < row.LastCellNum; j++)
{
ICell cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
continue;
} switch (cell.CellType)
{
case CellType.Boolean:
dataRow[j] = cell.BooleanCellValue;
break;
case CellType.Numeric:
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
default:
dataRow[j] = cell.ToString();
break;
}
}
dt.Rows.Add(dataRow);
}
return dt;
} private static DataTable SheetToDataTableHasTitle(ISheet sheet)
{
DataTable dt = new DataTable();
if (!string.IsNullOrWhiteSpace(sheet.SheetName))
{
dt.TableName = sheet.SheetName;
}
IRow firstRow = sheet.GetRow();
for (int i = ; i < firstRow.Cells.Count; i++)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
var colName = firstRow.GetCell(i).ToString();
colName = Regex.Replace(colName, @"\s", "");
if (dt.Columns[colName] == null)
{
dt.Columns.Add(colName);
}
else
{
dt.Columns.Add();
}
}
else
{
dt.Columns.Add();
}
}
for (int i = ; i <= sheet.LastRowNum; i++)
{
DataRow dataRow = dt.NewRow();
IRow row = sheet.GetRow(i);
if (row == null)
{
continue;
}
for (int j = ; j < firstRow.LastCellNum; j++)
{
ICell cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
continue;
} switch (cell.CellType)
{
case CellType.Boolean:
dataRow[j] = cell.BooleanCellValue;
break;
case CellType.Numeric:
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
default:
dataRow[j] = cell.ToString();
break;
}
}
dt.Rows.Add(dataRow);
} return dt;
} /// <summary>
/// 导出Excel数据填充
/// </summary>
/// <param name="dt"></param>
/// <param name="workBook"></param>
private static void DataTableFillWorkBook(DataTable dt, IWorkbook workBook, Dictionary<int, List<string>> dic = null)
{
var sheetName = dt.TableName;
if (string.IsNullOrWhiteSpace(sheetName))
{
sheetName = string.Format("sheet{0}", workBook.NumberOfSheets + );
}
ISheet sheet = workBook.CreateSheet(sheetName); if (dic != null && dic.Count > )
{
foreach (var item in dic.Keys)
{
if (dic[item] != null && dic[item].Count > )
{
CellRangeAddressList regions = new CellRangeAddressList(, , item, item);
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(dic[item].ToArray());
HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
sheet.AddValidationData(dataValidate);
}
}
} IRow firstRow = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
firstRow.CreateCell(i, CellType.String).SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + );
DataRow dtRow = dt.Rows[i];
for (int j = ; j < dt.Columns.Count; j++)
{
row.CreateCell(j, CellType.String).SetCellValue(dtRow[j].ToString());
}
}
} #endregion }
Dictionary<int, string> dicCurrencyType = EnumAttribute.GetEnumDictionary(typeof(CurrencyType));
Dictionary<string, string> dicIsInsured = new Dictionary<string, string>();
dicIsInsured.Add("true", "购买");
dicIsInsured.Add("false", "不购买"); //读取模版
string tplFilePath = Server.MapPath("~/Areas/YXExports/Content/Temp/order_lcl_templete.xls");
FileStream fs = System.IO.File.OpenRead(tplFilePath);
IWorkbook workBook = WorkbookFactory.Create(fs, ImportOption.All);
fs.Close();
fs.Dispose(); ISheet sheet2 = workBook.GetSheetAt();
for (int i = ; i < productList.Count; i++)
{
IRow row = sheet2.GetRow(i + );
if (row == null)
{
row = sheet2.CreateRow(i + );
}
ICell cell = row.GetCell();
if (cell == null)
{
cell = row.CreateCell();
}
cell.SetCellValue(productList[i].Name);
} for (int i = ; i < supportCountries.Count; i++)
{
IRow row = sheet2.GetRow(i + );
if (row == null)
{
row = sheet2.CreateRow(i + );
}
ICell cell = row.GetCell();
if (cell == null)
{
cell = row.CreateCell();
}
cell.SetCellValue(supportCountries[i].CnGeoName);
} //下拉框
ISheet sheet1 = workBook.GetSheetAt();
Dictionary<int, List<string>> dropDown = new Dictionary<int, List<string>>();
dropDown.Add(, productList.Select(l => l.Name).ToList());
dropDown.Add(, dicCurrencyType.Select(l => l.Key.ToString()).ToList());
dropDown.Add(, dicIsInsured.Select(l => l.Value.ToString()).ToList());
ExcelHelper.StructWorkbookDropdown(sheet1, dropDown); ExcelHelper.Export(workBook, string.Format(" {0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss")));
导出excel
DataTable dt = new DataTable();
dt.Columns.Add("公司名称");
dt.Columns.Add("客户邮箱"); foreach (var item in list)
{
DataRow dr = dt.NewRow();
dr["公司名称"] = item.CompanyName;
dr["客户邮箱"] = item.Email; dt.Rows.Add(dr); }
string fileName = string.Format("客户列表.xls");
ExcelHelper.Export(dt, fileName);
NPOI Helper文档的更多相关文章
- NPOI word文档表格在新的文档中多次使用
最近有一个项目,涉及到文档操作,有一个固定的模版,模版中有文字和表格,表格会在新的文档中使用n多次 //获取模版中的表格FileStream stream = new FileStream(strPa ...
- asp.net mvc4使用NPOI 数据处理之快速导出Excel文档
一.背景 在之前做的小项目里有一需求是:要求将一活动录入的数据进行统计,并以excel表格形式导出来,并且对表格格式要求并不高. 二.问题分析 鉴于用户只要求最终将数据库中的数据导出excel,对于格 ...
- 【转】ExcelHelper类,用npoi读取Excel文档
//------------------------------------------------------------------------------------- // All Right ...
- C# WebForm 使用NPOI 2 生成简单的word文档(.docx)
使用NPOI可以方便的实现服务端对Word.Excel的读写.要实现对Word的读写操作,需要引用NPOI.OOXML.dll,应用命名空间XWPF. 本文使用NPOI 2.0实现对Word的基本生成 ...
- MVC架构下,使用NPOI读取.DOCX文档中表格的内容
1.使用NPOI,可以在没有安装office的设备上读wiod.office.2.本文只能读取.docx后缀的文档.3.MVC架构中,上传文件只能使用form表单提交,转到控制器后要依次实现文件上传. ...
- .Net MVC+NPOI实现下载自定义的Word文档
我们浏览很多网站时都会看到下载文件的功能(图片.word文档等),好巧不巧的是贫道近日也遇到了这个问题,于是写一篇博客记录一下. 技术点:MVC.NPOI.Form表单. 具体如何实现,待贫道喝一口水 ...
- 利用NPOI生成word文档(c#)
WordTest.aspx.cs using System; using System.IO; using System.Text; using System.Web; using System.We ...
- NPOI 2.1.1 系列(2) 使用NPOI读取List或者datatable数据生成 Excel文档 ;Npoi生成 xlsx 2007以上文档
结合上一篇文章 NPOI 2.1.1 系列(1) 使用NPOI读取 Excel文档 ;NpoiExcelHelper 导入导出 2003格式 2007格式的 Excel; Npoi 导出 xlsx ...
- NPOI 2.1.1 系列(1) 使用NPOI读取 Excel文档 ;NpoiExcelHelper 导入导出 2003格式 2007格式的 Excel; Npoi 导出 xlsx 格式
下载地址 http://npoi.codeplex.com/releases 下面放一个 NPOIHelper 助手类吧,也不是我写的- NpoiExcelHelper 可以生成xlsx格式publi ...
随机推荐
- Linux下Tomcat服务器重启与关闭
Linux下Tomcat重新启动 详细请参照原网站链接http://www.cnblogs.com/tovep/articles/2473147.html 在Linux系统下,重启Tomcat使用命令 ...
- 【学】AngularJS日记(4)- 过滤器的使用
过滤器: 过滤器中的 |json,可以使原来的json数据输出时按照换行的样式 过滤器 | limitTo:2可以截取字符串或者数组的前2位 过滤器| orderBy 可以进行排序,加入json里的k ...
- 在.htaccess文件中写RewriteRule无效的问题的解决
近来在Apache Rewrite 拟静态配置时,遇到个问题.写的如下: RewriteEngine onRewriteRule ^/t_(.*)/$ /test.php?id=$1 保存在httpd ...
- 汇编语言学习与Makefile入门
继续开发 ; hello-os ; TAB= ORG 0x7c00 ; 指明程序的装载地址 ; 以下的记述用于标准FAT12格式的软盘 JMP entry DB 0x90 DB "HELLO ...
- ActiveX控件打包、签名、嵌入详解
ActiveX控件打包.签名.嵌入详解 前言 在我们的一个项目中,使用到了大华网络监控摄像头枪机,网络上下载了其ActiveX插件,但是发现其所提供的类库没有打包处理.这就导致我们每次给用户安装的时候 ...
- Android开发资料学习(转载/链接)
http://www.devdiv.com/android_-forum-102-1.html 各种开源控件集合 http://www.cnblogs.com/android-blogs/p/5342 ...
- iOS开发 - OC - PCH文件使用
一. PCH文件的作用 Xcode中,PCH文件在程序编译的时候会自动包含进去.也就是说PCH中的内容是全局的,可以使用在程序的任何地方,通过这个特性,我们可以概括到PCH的作用有以下几个方面: (1 ...
- WORD的公式无法与文字对齐
在使用Mathtype编辑公式后,经常出现以下公式与文字无法对齐的问题: 可以使用以下方式来解决:
- js中使用进行字符串传参
在js中拼接html标签传参时,如果方法参数是字符串需要加上引号,这里需要进行字符转义 <a href='javascript:addMenuUI("+"\"&qu ...
- .gitignore 使用中注意的问题
在git中如果想忽略掉某个文件,不让这个文件提交到版本库中,可以使用修改 .gitignore 文件的方法.这个文件每一行保存了一个匹配的规则例如: # 此为注释 – 将被 Git 忽略 *.a ...