Ionic2+WebApi 导出Excel转Pdf文件。

2023-10-18 08:59
文章标签 excel 导出 pdf webapi ionic2

本文主要是介绍Ionic2+WebApi 导出Excel转Pdf文件。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

步骤:

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

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

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

 

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

以下是H5的页面效果图,最终导出的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的效果

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的效果

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);
});
}
});
}
那么最后祝贺下我的小成果吧,啦啦啦~

转载于:https://www.cnblogs.com/smalldragon-hyl/p/8930763.html

这篇关于Ionic2+WebApi 导出Excel转Pdf文件。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/231565

相关文章

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

Python实现PDF按页分割的技术指南

《Python实现PDF按页分割的技术指南》PDF文件处理是日常工作中的常见需求,特别是当我们需要将大型PDF文档拆分为多个部分时,下面我们就来看看如何使用Python创建一个灵活的PDF分割工具吧... 目录需求分析技术方案工具选择安装依赖完整代码实现使用说明基本用法示例命令输出示例技术亮点实际应用场景扩

Python使用openpyxl读取Excel的操作详解

《Python使用openpyxl读取Excel的操作详解》本文介绍了使用Python的openpyxl库进行Excel文件的创建、读写、数据操作、工作簿与工作表管理,包括创建工作簿、加载工作簿、操作... 目录1 概述1.1 图示1.2 安装第三方库2 工作簿 workbook2.1 创建:Workboo

SpringBoot集成EasyPoi实现Excel模板导出成PDF文件

《SpringBoot集成EasyPoi实现Excel模板导出成PDF文件》在日常工作中,我们经常需要将数据导出成Excel表格或PDF文件,本文将介绍如何在SpringBoot项目中集成EasyPo... 目录前言摘要简介源代码解析应用场景案例优缺点分析类代码方法介绍测试用例小结前言在日常工作中,我们经

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并