Ionic2+WebApi 导出Excel转Pdf文件。

步骤:

1.首先在WebApi中先把excel生成好。

2.把excel转成Pdf,并返回下载的链接。

3.Ionic2的页面做好下载的接口。

嗯~思路很清晰,那么下面就来详细的操作吧。

以下是H5的页面效果图,最终导出的pdf也是如此。

Ionic2+WebApi 导出Excel转Pdf文件。

The First Step

一、把 数据字典转成 excel

以下是数据的结构

/// <summary>
/// 统计分析
/// </summary>
public class AnalysisResultToTable
{
public string XZQMC { get; set; }
public List<ResultToYears> Data { get; set; }

}
public class ResultToYears
{
public string Year { get; set; }
public Quarter Quarters { get; set; }
}
/// <summary>
/// 季度
/// </summary>
public class Quarter
{
/// <summary>
/// 第一季度
/// </summary>
public string FirstQuarter { get; set; }
/// <summary>
/// 第二季度
/// </summary>
public string TwoQuarter { get; set; }
/// <summary>
/// 第三季度
/// </summary>
public string ThreeQuarter { get; set; }
/// <summary>
/// 第四季度
/// </summary>
public string FourQuarter { get; set; }
}

1)这个是别人写好的服务,拿到这个数据。

maps = service.DB_Statistic_ReportXZMJ(year, mjdw, createman, area);

2)接着这个就是我做的需要把maps里的数据转成excel 。

file = service.DB_Statistic_Report_Export(detailName, year, maps);

以下是DB_Statistic_Report_Export的具体代码包括设计excel的样式

/// <summary>
/// 统计分析导出--表
/// </summary>
/// <param name="year">年份</param>
/// <param name="mjdw">面积单位</param>
/// <param name="createman">登录名(如果用户名为空,表示查询区域)</param>
/// <param name="area">区域</param>
/// <returns></returns>
public Stream DB_Statistic_Report_Export(string type,string year, Dictionary<string, AnalysisResultToTable> dic)
{
var headName = "临沂市" + type;
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet = hssfworkbook.CreateSheet(headName);
IRow row0 = sheet.CreateRow(0);
//样式一
var style= ExcelHelper.SetCellStyle(hssfworkbook, BorderStyle.Thin, HSSFColor.RoyalBlue.Index, HSSFColor.White.Index);

//样式二
var style1 = ExcelHelper.SetCellStyle(hssfworkbook, BorderStyle.Thin,HSSFColor.DarkTeal.Index,HSSFColor.White.Index);

//样式三
ICellStyle style2 = hssfworkbook.CreateCellStyle();
//水平对齐居中
style2.Alignment = HorizontalAlignment.Center;//水平对齐居中
style2.VerticalAlignment = VerticalAlignment.Center;//垂直居中
//标题
var yearArray = year.Split(',');
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4 * yearArray.Length));
ICell cell = row0.CreateCell(0);
cell.SetCellValue(headName);
cell.CellStyle = style2;

//第二行 年份 第三行 季度
IRow row1 = sheet.CreateRow(1);
IRow row2 = sheet.CreateRow(2);
for (int i = 0; i < yearArray.Length; i++)
{
ICell cell1 = row1.CreateCell(4 * i + 1);
cell1.SetCellValue(yearArray[i]);
sheet.AddMergedRegion(new CellRangeAddress(1, 1, 4 * i + 1, 4 * (i + 1)));
cell1.CellStyle = style;
ICell cell2_1 = row2.CreateCell(i * 4 + 1);
cell2_1.SetCellValue("第一季度");
ICell cell2_2 = row2.CreateCell(i * 4 + 2);
cell2_2.SetCellValue("第二季度");
ICell cell2_3 = row2.CreateCell(i * 4 + 3);
cell2_3.SetCellValue("第三季度");
ICell cell2_4 = row2.CreateCell(i * 4 + 4);
cell2_4.SetCellValue("第四季度");
cell2_1.CellStyle = style1;
cell2_2.CellStyle = style1;
cell2_3.CellStyle = style1;
cell2_4.CellStyle = style1;

}
//第二行和第三行的第一列合并 为临沂市
ICell cell0_1 = row1.CreateCell(0);
cell0_1.SetCellValue("临沂市");
sheet.AddMergedRegion(new CellRangeAddress(1, 2, 0, 0));
cell0_1.CellStyle = style1;

//数据列表
int j = 1;
foreach (string key in dic.Keys)
{
IRow row = sheet.CreateRow(2 + j);
//区县名
ICell celli_0 = row.CreateCell(0);
celli_0.SetCellValue(dic[key].XZQMC);
for (int i = 0; i < yearArray.Length; i++)
{
var Data = dic[key].Data.OrderBy(p => p.Year).ToList();
//4个季度
ICell celli_1 = row.CreateCell(4 * i + 1);
celli_1.SetCellValue(Data[i].Quarters.FirstQuarter);
ICell celli_2 = row.CreateCell(4 * i + 2);
celli_2.SetCellValue(Data[i].Quarters.TwoQuarter);
ICell celli_3 = row.CreateCell(4 * i + 3);
celli_3.SetCellValue(Data[i].Quarters.ThreeQuarter);
ICell celli_4 = row.CreateCell(4 * i + 4);
celli_4.SetCellValue(Data[i].Quarters.FourQuarter);
if (j % 2 == 0)
{
celli_0.CellStyle = style1;
celli_1.CellStyle = style1;
celli_2.CellStyle = style1;
celli_3.CellStyle = style1;
celli_4.CellStyle = style1;
}
else
{
celli_0.CellStyle = style;
celli_1.CellStyle = style;
celli_2.CellStyle = style;
celli_3.CellStyle = style;
celli_4.CellStyle = style;
}
}
j++;
}

//转换为文件流
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
file.Seek(0, SeekOrigin.Begin);

return file;
}

//给单元格设置样式的公共方法

/// <summary>
/// Excel帮助类
/// </summary>
public class ExcelHelper
{
/// <summary>
/// 设置单元格样式
/// </summary>
/// <param name="hssfworkbook">工作本</param>
/// <param name="borderStyle">边框样式</param>
/// <param name="borderColor">边框颜色</param>
/// <returns>ICellStyle</returns>
public static ICellStyle SetCellStyle(HSSFWorkbook hssfworkbook, BorderStyle borderStyle,short bgColor,short borderColor)
{
ICellStyle style = hssfworkbook.CreateCellStyle();
//背景颜色
style.FillForegroundColor = bgColor;
style.FillPattern = FillPattern.SolidForeground;
//水平对齐居中
style.Alignment = HorizontalAlignment.Center;//水平对齐居中
style.VerticalAlignment = VerticalAlignment.Center;//垂直居中
//边框及颜色
style.BorderBottom = borderStyle;
style.BorderLeft = borderStyle;
style.BorderRight = borderStyle;
style.BorderTop = borderStyle;
style.BottomBorderColor = borderColor;
style.LeftBorderColor = borderColor;
style.RightBorderColor = borderColor;
style.TopBorderColor = borderColor;

return style;
}
}

3) 然后把file存到服务器的本地文件中。

string name = year + "_" + detailName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");//xls文件名

using (FileStream fs = new FileStream(excelSavePath + name+".xls", FileMode.Create))//excelSavePath 服务器地址

{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
file.Seek(0, SeekOrigin.Begin);
//参数:要写入到文件的数据数组,从数组的第几个开始写,一共写多少个字节
fs.Write(bytes, 0, bytes.Length);
}

以下是excel的效果

Ionic2+WebApi 导出Excel转Pdf文件。

The Second Step

二、把  excel转成Pdf

ApiCommon.OfficeToPdf officeToPdf = new ApiCommon.OfficeToPdf();
officeToPdf.ConverterToPdf(excelSavePath + name + ".xls", pdfSavePath + name + ".pdf");
return ApiResult.Success(PDFPathDownload+name+".pdf");//返回服务器下载地址

以下是具体的excel转pdf代码

namespace Ionic_Server.ApiCommon
{
/// <summary>
/// 把 Office转成Pdf
/// </summary>
public class OfficeToPdf
{
/// <summary>
/// 转换excel 成PDF文档
/// </summary>
/// <param name="_lstrInputFile">原文件路径</param>
/// <param name="_lstrOutFile">pdf文件输出路径</param>
/// <returns>true 成功</returns>
public bool ConverterToPdf(string _lstrInputFile, string _lstrOutFile)
{
Microsoft.Office.Interop.Excel.Application lobjExcelApp = null;
Microsoft.Office.Interop.Excel.Workbooks lobjExcelWorkBooks = null;
Microsoft.Office.Interop.Excel.Workbook lobjExcelWorkBook = null;

string lstrTemp = string.Empty;
object lobjMissing = System.Reflection.Missing.Value;

try
{
lobjExcelApp = new Microsoft.Office.Interop.Excel.Application();
lobjExcelApp.Visible = true;
lobjExcelWorkBooks = lobjExcelApp.Workbooks;
lobjExcelWorkBook = lobjExcelWorkBooks.Open(_lstrInputFile, true, true, lobjMissing, lobjMissing, lobjMissing, true,
lobjMissing, lobjMissing, lobjMissing, lobjMissing, lobjMissing, false, lobjMissing, lobjMissing);

//Microsoft.Office.Interop.Excel 12.0.0.0之后才有这函数
lstrTemp = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls" + (lobjExcelWorkBook.HasVBProject ? 'm' : 'x');
//lstrTemp = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls";
//pdf临时存放路径
string pdfSavePath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
lobjExcelWorkBook.SaveAs(@pdfSavePath+ Guid.NewGuid().ToString() + ".xls");
//lobjExcelWorkBook.SaveAs(lstrTemp, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel4Workbook, Type.Missing, Type.Missing, Type.Missing, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,
// false, Type.Missing, Type.Missing, Type.Missing);
//输出为PDF 第一个选项指定转出为PDF,还可以指定为XPS格式
lobjExcelWorkBook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, _lstrOutFile, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, Type.Missing, false, Type.Missing, Type.Missing, false, Type.Missing);

lobjExcelWorkBooks.Close();
lobjExcelApp.Quit();
lobjExcelApp = null;
GC.Collect();//垃圾回收

}
catch (Exception ex)
{
LogAPI.Error(ex);
return false;
}
return true;
}
}
}

以下是pdf的效果

Ionic2+WebApi 导出Excel转Pdf文件。

The Third Step

三、在Ionic的ts代码中写对应的下载代码

//引用
import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
 
//构造函数
constructor( 
private transfer: FileTransfer,
private file: File,
) {}
 
//导出
Export() {
 ...
if (url != "") {
this.service.get(url).then(data => {
if (data != null) {
this.ExportData = data;
var fileTransfer: FileTransferObject = this.transfer.create();
var url = this.ExportData.Message;
fileTransfer.download(url, this.file.dataDirectory + 'file.xls').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
console.log(error);
});
}
});
}
 
那么最后祝贺下我的小成果吧,啦啦啦~
上一篇:Thread类源码剖析


下一篇:vue生命周期理解图