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 ...
随机推荐
- VirtrualBox使用已存在的镜像创建虚拟机
再将一个已经存在的虚拟机镜像拷贝为另一个新的虚拟机镜像后,要将该新的镜像添加到新的虚拟机中时会出现错误提示,从而导致不能创建虚拟机.例如有'D:\App\VirtualBox VMs\CentOS_6 ...
- BFS与DFS
DFS:使用栈保存未被检测的结点,结点按照深度优先的次序被访问并依次被压入栈中,并以相反的次序出栈进行新的检测. 类似于树的先根遍历深搜例子:走迷宫,你没有办法用分身术来站在每个走过的位置.不撞南山不 ...
- Oracle Merge备忘示例
Oracle的merge语法非常实用,用于Insert.Update判断情况.以下是自己书写的一个示例,以免时间长了语法形式忘记了. MERGE INTO T_FR_GUOSZX T USING (S ...
- ThinkPHP3.2.3 跨域访问
其他程序调用tp项目的action时需要进行跨域设置,在tp项目根目录下添加crossdomain.xml文件. 文件内容: <?xml version="1.0"?> ...
- Eclipse连接VirtualBox中的Android x86
Android x86 Alt+F1打开命令行,命令netcfg查看当前ip,记住,然后Alt+F7回界面. Eclipse-Window-Preferences-Android-DDMS-Use A ...
- 坦克大战,看你能坚持几秒 ~~Duang~~Duang
闲来无事,写了一个坦克大战的小游戏,打开页面就能看到源码,代码还没有来得及整理.大家闲来玩玩吧,看谁玩的时间长! http://xiaohaibaomu.com/home/index
- Python基础篇【第5篇】: Python模块基础(一)
模块 简介 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就 ...
- Unity3D 事件
unity3d事件函数整理,事件,回调函数,消息处理 Unity3D中所有控制脚本的基类MonoBehaviour有一些虚函数用于绘制中事件的回调,也可以直接理解为事件函数,例如大家都很清楚的Star ...
- Esfog_UnityShader教程_溶解效果Dissolve
溶解效果在游戏中是很常见的,比如在一些神话或者魔法世界中,一些NPC角色在剧情需要时候会身体会渐渐的消失掉.甚至有一些更炫的,比如用火焰喷射器把目标燃尽.这些都可以用到溶解效果.这篇文章主要是讲解一下 ...
- Manually enable Appear Offline in Lync 2013 Preview via Registry
refer to http://www.shudnow.net/2012/09/18/manually-enable-appear-offline-in-lync-2013-preview-via-r ...