发布:2020/2/12 13:37:11作者:管理员 来源:本站 浏览次数:1347
很简单直接上代码:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Converter;
/// <summary>
/// (NPOI)Excel转HTML
/// </summary>
/// <param name="HtmlName">HTML文件的的名称(不带后缀)</param>
/// <param name="Filename">需要转换Excel的绝对路径</param>
/// <returns></returns>
public string ExcelToHtml(string HtmlName, string Filename)
{
IWorkbook workbook;
//获取后缀名称
string fileExt = Path.GetExtension(Filename).ToLower();
//判断是否可以打开该文件,如果出错则文件已经打开或者有异常
try
{
System.IO.FileStream stream = System.IO.File.OpenWrite(Filename);
stream.Close();
}
catch
{
return null;
}
using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read))
{
//如果是XLSX格式选择XSSFWorkbook ,如果是XLS格式选择HSSFWorkbook
if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
if (workbook == null) { return null; }
}
ExcelToHtmlConverter eth = new ExcelToHtmlConverter();
// 设置输出参数
eth.OutputColumnHeaders = true; //是否输出ColumnHeader
eth.OutputHiddenColumns = false;//是否在表头插入一行序列号
eth.OutputHiddenRows = false;//是否输出HiddenRow
eth.OutputLeadingSpacesAsNonBreaking = true; //不清楚
eth.OutputRowNumbers = false;//是否在列头插入一行序列号
eth.UseDivsToSpan = false; //不清楚
// 加载Excel文件
eth.ProcessWorkbook(workbook);
// 保存文件值当前路径
string htmlFile =Application.StartupPath + "\\" + HtmlName + ".html";
eth.Document.Save(htmlFile);
return htmlFile;
}
————————————————