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文档的更多相关文章

  1. NPOI word文档表格在新的文档中多次使用

    最近有一个项目,涉及到文档操作,有一个固定的模版,模版中有文字和表格,表格会在新的文档中使用n多次 //获取模版中的表格FileStream stream = new FileStream(strPa ...

  2. asp.net mvc4使用NPOI 数据处理之快速导出Excel文档

    一.背景 在之前做的小项目里有一需求是:要求将一活动录入的数据进行统计,并以excel表格形式导出来,并且对表格格式要求并不高. 二.问题分析 鉴于用户只要求最终将数据库中的数据导出excel,对于格 ...

  3. 【转】ExcelHelper类,用npoi读取Excel文档

    //------------------------------------------------------------------------------------- // All Right ...

  4. C# WebForm 使用NPOI 2 生成简单的word文档(.docx)

    使用NPOI可以方便的实现服务端对Word.Excel的读写.要实现对Word的读写操作,需要引用NPOI.OOXML.dll,应用命名空间XWPF. 本文使用NPOI 2.0实现对Word的基本生成 ...

  5. MVC架构下,使用NPOI读取.DOCX文档中表格的内容

    1.使用NPOI,可以在没有安装office的设备上读wiod.office.2.本文只能读取.docx后缀的文档.3.MVC架构中,上传文件只能使用form表单提交,转到控制器后要依次实现文件上传. ...

  6. .Net MVC+NPOI实现下载自定义的Word文档

    我们浏览很多网站时都会看到下载文件的功能(图片.word文档等),好巧不巧的是贫道近日也遇到了这个问题,于是写一篇博客记录一下. 技术点:MVC.NPOI.Form表单. 具体如何实现,待贫道喝一口水 ...

  7. 利用NPOI生成word文档(c#)

    WordTest.aspx.cs using System; using System.IO; using System.Text; using System.Web; using System.We ...

  8. 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 ...

  9. NPOI 2.1.1 系列(1) 使用NPOI读取 Excel文档 ;NpoiExcelHelper 导入导出 2003格式 2007格式的 Excel; Npoi 导出 xlsx 格式

    下载地址 http://npoi.codeplex.com/releases 下面放一个 NPOIHelper 助手类吧,也不是我写的- NpoiExcelHelper 可以生成xlsx格式publi ...

随机推荐

  1. 黄聪:C#中HtmlAgilityPack判断是否包含或不包含指定的属性或值

    //选择不包含class属性的节点 var result = node.SelectNodes(".//span[not(@class)]"); //选择不包含class和id属性 ...

  2. 带无缝滚动的轮播图(含JS运动框架)-简洁版

    昨天写的神逻辑,今天终于解决,经过大家的商讨,终于研究出来一套简单的代码!!! js代码如下: <script> window.onload = function() { var oWra ...

  3. 彻底搞定char/wchar_t/unicode

    彻底搞定char/wchar_t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! (2013-07-17 10:18:28) 转载▼     从char/wchar_t到TCHAR(1) ...

  4. iptables删除规则

    查看nat规则: iptables -t nat -nL --line-number 添加规则是-A和-I,-A是添加到末尾,-I是添加到指定位置,默认添加到最前面.删除使用-D,也就是原来“ipta ...

  5. 01-C#入门(函数一)

    只有在动手写代码的时候,才能真正理解到代码的逻辑思想,所以,开始写代码吧. 函数的意义:降低相同功能的代码重复编写,提高重复代码的维护效率. 函数 一个文件由命令空间(namespace).类(cla ...

  6. Android SQLiteOpenHelper类的使用

    SQLiteOpenHelper类是Android平台提供的用于SQLite数据库的创建.打开以及版本管理的帮助类.一般需要继承并这个类并实现它的onCreate和onUpgrade方法,在构造方法中 ...

  7. 学习indy组件之一idhttp的使用方法

    登录 注册 百度首页 新闻 网页 贴吧 知道 音乐 图片 视频 地图 百科 文库 经验 搜索答案我要提问 首页 分类 公社 知道行家 问医生 高质量问答 经验 个人中心手机知道开放平台   关于del ...

  8. Struts2:类型转换器

    常规的String,int能自动转换,但是,有些类型不是这么简单,比如输入字符串,但需要Date.自定义类型,因此需要自定义类型转换类型转换器分全局和局部按惯例,局部的优先级高于全局 需求: 1.输入 ...

  9. Python Quick list dir

    昨天 Python释放了 3.5 ,添加了 os.scandir 根据文档该API比os.listdir快Docs which speeds it up by 3-5 times on POSIX s ...

  10. 《JavaScript高级程序设计》学习笔记(3)——变量、作用域和内存问题

    欢迎关注本人的微信公众号"前端小填填",专注前端技术的基础和项目开发的学习. 本节内容对应<JavaScript高级程序设计>的第四章内容. 1.函数:通过函数可以封装 ...