Mvc 拼接Html 导出 Excel(服务器不用安装呦!支持2007以上版本)

时间:2022-05-07 03:19:11

  新公司,新接触,老方法,更实用。

  之前接触过Webform,winfrom 的导出Excel方法 ,优点:省事。缺点:服务器必须安装Office

  这几天做项目 和 大牛学习了一下 新的方法,自己加以总结。希望更多的博友获益。不多说 。先上图,后上源码。

  很简单的MVC4 的页面 献丑了

  Mvc 拼接Html 导出 Excel(服务器不用安装呦!支持2007以上版本)

效果图

  Mvc 拼接Html 导出 Excel(服务器不用安装呦!支持2007以上版本)

  你猜了对了  我用的是 ClosedXml、NPOI  不是很新的东西!

  看看代码怎么实现吧 !

  1、工厂封装直接调用:

   public class ExportFactory
{
public static byte[] exportToExcel(string type)
{
byte[] bytes = null;
switch (type.ToLower())
{
case "npoi":
bytes = NpoiExcelHelp.GenerateXlsxBytes(GetHtml());
break;
case "closexml":
bytes = ClosedXmlExcelHelp.GenerateXlsxBytes(GetHtml());
break;
default:
break;
}
return bytes;
} static string GetHtml()
{
StringBuilder strHtml = new StringBuilder();
strHtml.Append("<table>");
strHtml.Append("<tr>");
strHtml.Append("<td rowspan='2'>First Row/First Colunm</td>");
strHtml.Append("<td>Second Row/First Colunm</td>");
strHtml.Append("</tr>");
strHtml.Append("<tr>");
strHtml.Append("<td>First Row/Second Colunm</td>");
strHtml.Append("</tr>");
strHtml.Append("<tr>");
strHtml.Append("<td>Second Row/Second Colunm</td>");
strHtml.Append("<td>Third Row/Second Colunm</td>");
strHtml.Append("</tr>");
strHtml.Append("</table>");
return strHtml.ToString();
}
}

  2、ClosedXmlExportHelp

   public class ClosedXmlExcelHelp
{
public static byte[] GenerateXlsxBytes(string tableHtml)
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + tableHtml; XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); XmlNode table = doc.SelectSingleNode("/table"); int colspan = ;
int rowspan = ; var workBook = new XLWorkbook();
var ws = workBook.Worksheets.Add("Export"); int rowNum;
int columnNum; rowNum = ;
columnNum = ; string mapKey = string.Empty;
string mergKey = string.Empty; int rowCount = table.ChildNodes.Count;
int colCount = ; foreach (XmlNode row in table.ChildNodes)
{
if (colCount < row.ChildNodes.Count)
{
colCount = row.ChildNodes.Count;
}
} bool[,] map = new bool[rowCount + , colCount + ]; foreach (XmlNode row in table.ChildNodes)
{
columnNum = ;
foreach (XmlNode column in row.ChildNodes)
{
if (column.Attributes["rowspan"] != null)
{
rowspan = Convert.ToInt32(column.Attributes["rowspan"].Value);
}
else
{
rowspan = ;
} if (column.Attributes["colspan"] != null)
{
colspan = Convert.ToInt32(column.Attributes["colspan"].Value);
}
else
{
colspan = ;
} while (map[rowNum, columnNum])
{
columnNum++;
} if (rowspan == && colspan == )
{
ws.Cell(string.Format("{0}{1}", Char.Chr(columnNum), rowNum)).Value = column.InnerText;
map[rowNum, columnNum] = true;
}
else
{
ws.Cell(string.Format("{0}{1}", Char.Chr(columnNum), rowNum)).Value = column.InnerText;
mergKey =
string.Format("{0}{1}:{2}{3}",
Char.Chr(columnNum), rowNum, Char.Chr(columnNum + colspan - ), rowNum + rowspan - );
ws.Range(mergKey).Merge(); for (int m = ; m < rowspan; m++)
{
for (int n = ; n < colspan; n++)
{
map[rowNum + m, columnNum + n] = true;
}
}
}
columnNum++;
}
rowNum++;
} MemoryStream stream = new MemoryStream();
workBook.SaveAs(stream); return stream.ToArray(); }
}

  3、NPOIExportHelp

   public class NpoiExcelHelp
{
public static byte[] GenerateXlsxBytes(string tableHtml)
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + tableHtml; XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); XmlNode table = doc.SelectSingleNode("/table"); int colspan = ;
int rowspan = ; int rowNum;
int columnNum;
rowNum = ;
columnNum = ; var workBook = new HSSFWorkbook();
var ws = workBook.CreateSheet("Export"); string mapKey = string.Empty;
string mergKey = string.Empty; int rowCount = table.ChildNodes.Count;
int colCount = FetchColCount(table.ChildNodes); InitSheet(ws, rowCount, colCount); bool[,] map = new bool[rowCount + , colCount + ]; foreach (XmlNode row in table.ChildNodes)
{
columnNum = ;
foreach (XmlNode column in row.ChildNodes)
{
if (column.Attributes["rowspan"] != null)
{
rowspan = Convert.ToInt32(column.Attributes["rowspan"].Value);
}
else
{
rowspan = ;
} if (column.Attributes["colspan"] != null)
{
colspan = Convert.ToInt32(column.Attributes["colspan"].Value);
}
else
{
colspan = ;
} while (map[rowNum, columnNum])
{
columnNum++;
} if (rowspan == && colspan == )
{
SetCellValue(ws, string.Format("{0}{1}", Char.Chr(columnNum), rowNum), column.InnerText);
map[rowNum, columnNum] = true;
}
else
{
SetCellValue(ws, string.Format("{0}{1}", Char.Chr(columnNum), rowNum), column.InnerText);
mergKey =
string.Format("{0}{1}:{2}{3}",
Char.Chr(columnNum), rowNum, Char.Chr(columnNum + colspan - ), rowNum + rowspan - );
MergCells(ws, mergKey); for (int m = ; m < rowspan; m++)
{
for (int n = ; n < colspan; n++)
{
map[rowNum + m, columnNum + n] = true;
}
}
}
columnNum++;
}
rowNum++;
} MemoryStream stream = new MemoryStream();
workBook.Write(stream); return stream.ToArray(); } static int FetchColCount(XmlNodeList nodes)
{
int colCount = ; foreach (XmlNode row in nodes)
{
if (colCount < row.ChildNodes.Count)
{
colCount = row.ChildNodes.Count;
}
} return colCount;
} static void InitSheet(ISheet sheet, int rowCount, int colCount)
{
for (int i = ; i < rowCount; i++)
{
IRow row = sheet.CreateRow(i);
for (int j = ; j < colCount; j++)
{
row.CreateCell(j);
}
}
} static void SetCellValue(ISheet sheet, string cellReferenceText, string value)
{
CellReference cr = new CellReference(cellReferenceText);
IRow row = sheet.GetRow(cr.Row);
ICell cell = row.GetCell(cr.Col);
cell.SetCellValue(value);
} static void MergCells(ISheet sheet, string mergeKey)
{
string[] cellReferences = mergeKey.Split(':'); CellReference first = new CellReference(cellReferences[]);
CellReference last = new CellReference(cellReferences[]); CellRangeAddress region = new CellRangeAddress(first.Row, last.Row, first.Col, last.Col);
sheet.AddMergedRegion(region);
}
}

  4、Ascii 转化

  public class Char
{
public static string Chr(int i)
{
char c = (char)( + i);
return c.ToString();
}
}

   5、EpplusExportHelp (office 2007 以上版本)

   public class EpplusExcelHelp
{ public static byte[] GenerateXlsxBytes2007(string tableHtml)
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + tableHtml; XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); XmlNode table = doc.SelectSingleNode("/table"); int colspan = ;
int rowspan = ; int rowNum;
int columnNum;
rowNum = ;
columnNum = ; ExcelPackage excel = new ExcelPackage();
ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Export"); int rowCount = table.ChildNodes.Count;
int colCount = FetchColCount(table.ChildNodes); bool[,] map = new bool[rowCount + , colCount + ];
MemoryStream stream = new MemoryStream();
try
{
foreach (XmlNode row in table.ChildNodes)
{
columnNum = ;
foreach (XmlNode column in row.ChildNodes)
{
if (column.Attributes["rowspan"] != null)
{
rowspan = Convert.ToInt32(column.Attributes["rowspan"].Value);
}
else
{
rowspan = ;
} if (column.Attributes["colspan"] != null)
{
colspan = Convert.ToInt32(column.Attributes["colspan"].Value);
}
else
{
colspan = ;
} while (map[rowNum, columnNum])
{
columnNum++;
} if (rowspan == && colspan == )
{
worksheet.Cells[rowNum, columnNum].Value = column.InnerText;
}
else
{
worksheet.Cells[rowNum, columnNum, rowNum + rowspan - , columnNum + colspan - ].Merge = true;
worksheet.Cells[rowNum, columnNum].Value = column.InnerText;
for (int m = ; m < rowspan; m++)
{
for (int n = ; n < colspan; n++)
{
map[rowNum + m, columnNum + n] = true;
}
}
}
columnNum++;
}
rowNum++;
}
worksheet.Cells.Style.ShrinkToFit = true; excel.SaveAs(stream); return stream.ToArray();
}
catch (Exception ex)
{ throw ex;
}
finally
{
stream.Close();
}
} static int FetchColCount(XmlNodeList nodes)
{
int colCount = ; foreach (XmlNode row in nodes)
{
if (colCount < row.ChildNodes.Count)
{
colCount = row.ChildNodes.Count;
}
} return colCount;
}
}

  以上代码就是实现Export Excel的全部代码

   思路:拼接字符串构造一个纯Html的结构。用rowspan colspan来跨行跨列,把Html当做参数直接传过去调用写好的导出方法

   返回数组。保存 完成!很简单!

   希望能帮助大家!我的可能不是最好的方法!但是我在尽力去想!希望广大的博友一起想!想出更好的方法解决中国的所有技术人员的困惑!如有想法请留下您的宝贵评论!

Check Me Give You Source!