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实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

Python实现pdf电子发票信息提取到excel表格

《Python实现pdf电子发票信息提取到excel表格》这篇文章主要为大家详细介绍了如何使用Python实现pdf电子发票信息提取并保存到excel表格,文中的示例代码讲解详细,感兴趣的小伙伴可以跟... 目录应用场景详细代码步骤总结优化应用场景电子发票信息提取系统主要应用于以下场景:企业财务部门:需

Mac备忘录怎么导出/备份和云同步? Mac备忘录使用技巧

《Mac备忘录怎么导出/备份和云同步?Mac备忘录使用技巧》备忘录作为iOS里简单而又不可或缺的一个系统应用,上手容易,可以满足我们日常生活中各种记录的需求,今天我们就来看看Mac备忘录的导出、... 「备忘录」是 MAC 上的一款常用应用,它可以帮助我们捕捉灵感、记录待办事项或保存重要信息。为了便于在不同

Python处理大量Excel文件的十个技巧分享

《Python处理大量Excel文件的十个技巧分享》每天被大量Excel文件折磨的你看过来!这是一份Python程序员整理的实用技巧,不说废话,直接上干货,文章通过代码示例讲解的非常详细,需要的朋友可... 目录一、批量读取多个Excel文件二、选择性读取工作表和列三、自动调整格式和样式四、智能数据清洗五、

Python Pandas高效处理Excel数据完整指南

《PythonPandas高效处理Excel数据完整指南》在数据驱动的时代,Excel仍是大量企业存储核心数据的工具,Python的Pandas库凭借其向量化计算、内存优化和丰富的数据处理接口,成为... 目录一、环境搭建与数据读取1.1 基础环境配置1.2 数据高效载入技巧二、数据清洗核心战术2.1 缺失

利用Python实现Excel文件智能合并工具

《利用Python实现Excel文件智能合并工具》有时候,我们需要将多个Excel文件按照特定顺序合并成一个文件,这样可以更方便地进行后续的数据处理和分析,下面我们看看如何使用Python实现Exce... 目录运行结果为什么需要这个工具技术实现工具的核心功能代码解析使用示例工具优化与扩展有时候,我们需要将

Python对PDF书签进行添加,修改提取和删除操作

《Python对PDF书签进行添加,修改提取和删除操作》PDF书签是PDF文件中的导航工具,通常包含一个标题和一个跳转位置,本教程将详细介绍如何使用Python对PDF文件中的书签进行操作... 目录简介使用工具python 向 PDF 添加书签添加书签添加嵌套书签Python 修改 PDF 书签Pytho