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. php5.3到php7.0.x新特性介绍

    <?php /*php5.3*/ echo '<hr>'; const MYTT = 'aaa'; #print_r(get_defined_constants()); /* 5.4 ...

  2. View加载过程

    1. 先判断子类是否重写了loadView,如果有直接调用.之后调viewDidLoad完成View的加载.2 .如果是外部通过调用initWithNibName:bundle指定nib文件名的话,V ...

  3. android studio 各种问题

    1.dexDebug ExecException finished with non-zero exit value 2 全bug日志如下: (Error:Execution failed for t ...

  4. OAF_开发系列15_实现OAF组件重用和继承(案例)

    20150717 Created By BaoXinjian

  5. PL/SQLDeveloper导入导出Oracle数据库方法

    前一篇博客介绍了Navicat工具备份Oracle的方法,这篇博客介绍一下使用PL/SQL Developer工具导入导出Oracle数据库的方法. PL/SQL Developer是Oracle数据 ...

  6. PC机上的COM1口和COM2口

    现在PC机一般有两个串行口COM1和COM2. 串口叫串行接口 串口与并口不同之处:数据和控制信息时一位接一位地传送出去的,虽然速度慢,但传送距离较并口会更长,因此若要进行较长距离的通行时,应该使用串 ...

  7. sed字符串替换

    把drivers目录下的所有pr_log替换成:pr_snd sed -i "s/pr_log/pr_snd/g" `grep pr_log -rl drivers/` 把driv ...

  8. <-0基础学python.第2课->

    今天闲着无聊,有想鼓捣Python了,想实现网络爬虫,帮我下载音乐的功能. 现在网上找了相关的一些文章教程 http://jecvay.com/2014/09/python3-web-bug-seri ...

  9. C++设计模式-State状态模式

    State状态模式作用:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类. UML图如下: State类,抽象状态类,定义一个接口以封装与Context的一个特定状态相关的行为. ...

  10. 如何在centos 6.7 上安装oracle 11gR2

    1.软件准备: centos6.7(64位); oracle11gR2((Linux x86-64)) 2.执行如下命令安装好相关的包: yum -y install \ binutils \ com ...