1.导出Excel(列宽自适应,合并单元格)
JS
var iframeUrl = "自己控制方法路径";
var body = document.getElementsByTagName("body")[0];
var downloadIframe = document.createElement("iframe");
downloadIframe.setAttribute("src", iframeUrl);
downloadIframe.setAttribute("style", "display:none;")
body.appendChild(downloadIframe);
Controller
#region NPOI导出Excel
/// <summary>
/// 导出Excel
/// </summary>
public void ExportToExcel()
{
//获取要导出的数据
var exportData = new List<DataClass>() { new DataClass { CatalogID = "1", CatalogName = "第一个", DataName = "1" }, new DataClass { CatalogID = "1", CatalogName = "第一个", DataName = "110" }, new DataClass { CatalogID = "1", CatalogName = "第一个", DataName = "111" }, new DataClass { CatalogID = "1", CatalogName = "第一个第二级", DataName = "222" }, new DataClass { CatalogID = "1", CatalogName = "第一个第二级", DataName = "666" }, new DataClass { CatalogID = "2", CatalogName = "第二个", DataName = "2" }, new DataClass { CatalogID = "3", CatalogName = "第三个", DataName = "3" } };
//转成datatable
var dt = ListToDataTable(exportData);
//获取要导出的sheet名称数据
var exportObjData = new List<CatalogClass>() { new CatalogClass { CatalogID = "1", CatalogName = "第一个", FullPathCN = "1" }, new CatalogClass { CatalogID = "2", CatalogName = "第二个", FullPathCN = "2" }, new CatalogClass { CatalogID = "3", CatalogName = "第三个", FullPathCN = "3" } };
//用来获取要合并的列
string catalogName = "";
int stratindex = 1;
int endindex = 0;
//创建工作表
IWorkbook workbook = new XSSFWorkbook();
//样式
ICellStyle cellstyle = workbook.CreateCellStyle();
cellstyle.VerticalAlignment = VerticalAlignment.Center;
cellstyle.Alignment = HorizontalAlignment.Center;