C#用Aspose.Cells导出xls

2024-06-10 10:18

本文主要是介绍C#用Aspose.Cells导出xls,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 导出代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using WuZiFenGongSiInfomation.Common;namespace WuZiFenGongSiInfomation.Export
{/// <summary>/// 导出excel/// </summary>/// 2019-11-5 15:56:05   添加public class ExportExcelHelpter{/// <summary>/// 导出excel/// </summary>/// <param name="data">数据</param>/// <param name="stream">导出流</param>public static void ExportExcel(List<List<string>> data, ref Stream stream){Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook();Aspose.Cells.Worksheet sheet = wb.Worksheets[0];Aspose.Cells.Cells cells = sheet.Cells;Aspose.Cells.Style style = wb.Styles[wb.Styles.Add()];//style.Font.Name = "宋体";style.Font.Size = 12;cells.ApplyStyle(style, new StyleFlag() { All = true });int cols = data[0].Count;//标题样式Aspose.Cells.Style styleTitle = wb.Styles[wb.Styles.Add()];styleTitle.Font.IsBold = true;styleTitle.Font.Size = 12;Range range = cells.CreateRange(0, 0, 1, cols);range.ApplyStyle(styleTitle, new StyleFlag() { All = true });object[,] dataArr2 = new object[data.Count, cols];for (int n = 0; n < data.Count; n++){var rowLine = data[n];for (int j = 0; j < rowLine.Count; j++){dataArr2[n, j] = rowLine[j];}}cells.ImportTwoDimensionArray(dataArr2, 0, 0);//for (int i = 0; i < data.Count; i++)//{//    var item = data[i];//    for (int n = 0; n < item.Count; n++)//    {//        var valueCell = item[n];//        cells[i, n].PutValue(valueCell);//        if (i == 0)//        {//            cells[i, n].SetStyle(styleTitle);//        }//        else {//            cells[i, n].SetStyle(style);//        }//    }//}//自适应宽sheet.AutoFitColumns();//自适应行高sheet.AutoFitRows();string fileName = Guid.NewGuid().ToString("N") + ".xls";string filePath = AppDomain.CurrentDomain.BaseDirectory + fileName;//2020-8-5 09:53:58 添加string fileFolderDeire = Path.GetDirectoryName(filePath);//目录信息if (!System.IO.Directory.Exists(fileFolderDeire)){System.IO.Directory.CreateDirectory(fileFolderDeire);}//保存文件到本地wb.Save(filePath);stream.Seek(0, SeekOrigin.Begin);stream = new FileStream(filePath, FileMode.Open);Task.Run(() =>{//删除生成的文件System.Threading.Thread.Sleep(1000);try{File.Delete(filePath);}catch (Exception) { }});保存文件到本地//FileStream fileStream = new FileStream(filePath, FileMode.Create);//byte[] buff = new byte[stream.Length];stream.Write(buff, 0, (int)stream.Length);//stream.Read(buff,0, (int)stream.Length);//fileStream.Write(buff, 0, (int)stream.Length);//fileStream.Close();//fileStream.Dispose();}/// <summary>/// 导出excel文件,返回生成的web url地址/// </summary>/// <param name="data">导出的数据</param>/// <param name="fileName">生成的文件名称包含后缀</param>/// <returns></returns>public static string ExportExcelFile(List<List<string>> data, string fileName){Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook();Aspose.Cells.Worksheet sheet = wb.Worksheets[0];Aspose.Cells.Cells cells = sheet.Cells;Aspose.Cells.Style style = wb.Styles[wb.Styles.Add()];//style.Font.Name = "宋体";style.Font.Size = 11;cells.ApplyStyle(style, new StyleFlag() { All = true });int cols = data[0].Count;//标题样式Aspose.Cells.Style styleTitle = wb.Styles[wb.Styles.Add()];styleTitle.Font.IsBold = true;styleTitle.Font.Size = 11;Range range = cells.CreateRange(0, 0, 1, cols);range.ApplyStyle(styleTitle, new StyleFlag() { All = true });object[,] dataArr2 = new object[data.Count, cols];for (int n = 0; n < data.Count; n++){var rowLine = data[n];for (int j = 0; j < rowLine.Count; j++){dataArr2[n, j] = rowLine[j];}}cells.ImportTwoDimensionArray(dataArr2, 0, 0);//自适应宽//sheet.AutoFitColumns();//2020-7-10 14:22:50 注释//自适应行高sheet.AutoFitRows();//string fileName = Guid.NewGuid().ToString("N") + ".xls";string filePath = AppDomain.CurrentDomain.BaseDirectory + Models.Veiw.CommonData.ExportFilefolder + fileName;//2020-8-5 09:53:58 添加string fileFolderDeire =   Path.GetDirectoryName(filePath);//目录信息if (!System.IO.Directory.Exists(fileFolderDeire)) {               System.IO.Directory.CreateDirectory(fileFolderDeire);}//保存文件到本地wb.Save(filePath);string url = Models.Veiw.CommonData.ExportFilefolder.Replace(@"\", @"/") + fileName;//记录生成的文件到缓存,用于删除const string cacheKey = "XLS_EXPORT_TO_DEL";List<string> filesExportList = MemoryCacheProvider.GetCacheItem<List<string>>(cacheKey);if (filesExportList != null){//var item = (filePath, DateTime.UtcNow);filesExportList.Add(filePath);MemoryCacheProvider.Set(cacheKey, filesExportList, DateTime.UtcNow.AddMinutes(240));}else{filesExportList = new List<string>();filesExportList.Add(filePath);MemoryCacheProvider.Set(cacheKey, filesExportList, DateTime.UtcNow.AddMinutes(240));}//删除文件Task.Run(() =>{System.Threading.Thread.Sleep(300000);ac(filesExportList);});return url;}/// <summary>/// 导出excel文件,返回生成的web url地址/// </summary>/// <param name="data">导出的数据,List<string>是一行的数据</param>/// <param name="fileName">生成的文件名,比如test.xls</param>/// <param name="columnsWidthSet">设置列宽,TKey是列下标,第一列为0;TValue是列宽度</param>/// <returns></returns>public static string ExportExcelFile(List<List<string>> data, string fileName, SortedList<int, double> columnsWidthSet = null){Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook();Aspose.Cells.Worksheet sheet = wb.Worksheets[0];Aspose.Cells.Cells cells = sheet.Cells;Aspose.Cells.Style style = wb.Styles[wb.Styles.Add()];//style.Font.Name = "宋体";style.Font.Size = 11;cells.ApplyStyle(style, new StyleFlag() { All = true });int cols = data[0].Count;//标题样式Aspose.Cells.Style styleTitle = wb.Styles[wb.Styles.Add()];styleTitle.Font.IsBold = true;styleTitle.Font.Size = 11;Range range = cells.CreateRange(0, 0, 1, cols);range.ApplyStyle(styleTitle, new StyleFlag() { All = true });object[,] dataArr2 = new object[data.Count, cols];for (int n = 0; n < data.Count; n++){var rowLine = data[n];for (int j = 0; j < rowLine.Count; j++){dataArr2[n, j] = rowLine[j];}}cells.ImportTwoDimensionArray(dataArr2, 0, 0);//cells.SetColumnWidth(0, 31.29);//设置列宽,标题(第一列)//cells.SetColumnWidth(1, 9);//设置列宽,标题//cells.SetColumnWidth(2, 20.29);//设置列宽,标题标题//cells.SetColumnWidth(3, 30);//设置列宽,作者//cells.SetColumnWidth(4, 33);//设置列宽,栏目//cells.SetColumnWidth(6, 33);//设置列宽,意见//cells.SetColumnWidth(8, 23);//设置列宽,审核单位//cells.SetColumnWidth(9, 21.5);//设置列宽,审核时间if (columnsWidthSet!=null && columnsWidthSet.Count>0){foreach (var columsWidth in columnsWidthSet){cells.SetColumnWidth(columsWidth.Key, columsWidth.Value);//设置列宽}}//自适应宽            //sheet.AutoFitColumns();//2020-7-10 14:22:50 注释//自适应行高sheet.AutoFitRows();//string fileName = Guid.NewGuid().ToString("N") + ".xls";string filePath = AppDomain.CurrentDomain.BaseDirectory + Models.Veiw.CommonData.ExportFilefolder + fileName;//2020-8-5 09:53:58 添加string fileFolderDeire = Path.GetDirectoryName(filePath);//目录信息if (!System.IO.Directory.Exists(fileFolderDeire)){System.IO.Directory.CreateDirectory(fileFolderDeire);}//保存文件到本地wb.Save(filePath);string url = Models.Veiw.CommonData.ExportFilefolder.Replace(@"\", @"/") + fileName;//记录生成的文件到缓存,用于删除const string cacheKey = "XLS_EXPORT_TO_DEL";List<string> filesExportList = MemoryCacheProvider.GetCacheItem<List<string>>(cacheKey);if (filesExportList != null){//var item = (filePath, DateTime.UtcNow);filesExportList.Add(filePath);MemoryCacheProvider.Set(cacheKey, filesExportList, DateTime.UtcNow.AddMinutes(240));}else{filesExportList = new List<string>();filesExportList.Add(filePath);MemoryCacheProvider.Set(cacheKey, filesExportList, DateTime.UtcNow.AddMinutes(240));}//删除文件Task.Run(() =>{System.Threading.Thread.Sleep(300000);ac(filesExportList);});return url;}/// <summary>/// 删除已经过期的文件/// </summary>private readonly static Action<List<string>> ac = (list) =>{if (list == null || list.Count == 0){return;}foreach (var delFile in list){if (File.Exists(delFile)){File.Delete(delFile);}}};}
}

方法调用参考:

 //驳回记录 到处excel  2020-7-10 11:39:59 添加[LoginFilter(Roles = "2700400")]public async Task<ActionResult> ExportRejectRecord(CheckHistoryWhere where, int pageIndex = 1, int pageSize = 500){await Task.Yield();var page = await articleCheckHistoryBll.PageMyHistoryAsync(where, pageIndex, 1);int total = page?.Total ?? 0;int exportRows = CommonData.AllowExportRows;int pageCount = (int)Math.Ceiling((decimal)page.Total / (decimal)exportRows);List<string> fileUrls = new List<string>();List<List<string>> list = new List<List<string>>();for (; pageIndex <= pageCount; pageIndex++){list.Clear();List<CheckHistoryView> data = null;var page2 = await articleCheckHistoryBll.PageMyHistoryAsync(where, pageIndex, exportRows);if (page2?.List != null){data = page2.List;}if (data == null){return Content("没有数据导出");}//标题var row = new List<string>();row.Add("标题");row.Add("报送人");row.Add("报送单位");row.Add("作者");row.Add("报送栏目");row.Add("进度");row.Add("意见");row.Add("审核人");row.Add("审核单位");row.Add("审核时间");list.Add(row);//数据for (int i = 0; i < data.Count; i++){var item = data[i];var rowData = new List<string>();rowData.Add(item.Title);rowData.Add(item.Reportor);rowData.Add(item.ReportorDepartment);rowData.Add(item.AuthorStr);rowData.Add(item.ChannerName);rowData.Add(item.StepTxt);rowData.Add(item.Remark);rowData.Add(item.CheckUserName);rowData.Add(item.CheckUserDepartmentName);rowData.Add(item.CheckTime.ToString("yyyy-MM-dd HH:mm:ss"));list.Add(rowData);}string fileName = string.Empty;if (total < exportRows){fileName = Guid.NewGuid().ToString("N") + ".xls";}else{fileName = Guid.NewGuid().ToString("N") + "_" + pageIndex + ".xls";}SortedList<int, double> columnsWidth = new SortedList<int, double>();columnsWidth.Add(0, 31.29);//设置列宽,标题(第一列)columnsWidth.Add(1, 9);//设置列宽,标题columnsWidth.Add(2, 20.29);//设置列宽,标题标题columnsWidth.Add(3, 30);//设置列宽,作者columnsWidth.Add(4, 33);//设置列宽,栏目columnsWidth.Add(6, 33);//设置列宽,意见columnsWidth.Add(8, 23);//设置列宽,审核单位columnsWidth.Add(9, 21.5);//设置列宽,审核时间string url = ExportExcelHelpter.ExportExcelFile(list,"驳回记录"+ fileName,columnsWidth);fileUrls.Add(url);}return Json(new Result(fileUrls), JsonRequestBehavior.AllowGet);}

 

 

 

这篇关于C#用Aspose.Cells导出xls的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

一文解析C#中的StringSplitOptions枚举

《一文解析C#中的StringSplitOptions枚举》StringSplitOptions是C#中的一个枚举类型,用于控制string.Split()方法分割字符串时的行为,核心作用是处理分割后... 目录C#的StringSplitOptions枚举1.StringSplitOptions枚举的常用

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造

C#自动化实现检测并删除PDF文件中的空白页面

《C#自动化实现检测并删除PDF文件中的空白页面》PDF文档在日常工作和生活中扮演着重要的角色,本文将深入探讨如何使用C#编程语言,结合强大的PDF处理库,自动化地检测并删除PDF文件中的空白页面,感... 目录理解PDF空白页的定义与挑战引入Spire.PDF for .NET库核心实现:检测并删除空白页

C#利用Free Spire.XLS for .NET复制Excel工作表

《C#利用FreeSpire.XLSfor.NET复制Excel工作表》在日常的.NET开发中,我们经常需要操作Excel文件,本文将详细介绍C#如何使用FreeSpire.XLSfor.NET... 目录1. 环境准备2. 核心功能3. android示例代码3.1 在同一工作簿内复制工作表3.2 在不同

C#中通过Response.Headers设置自定义参数的代码示例

《C#中通过Response.Headers设置自定义参数的代码示例》:本文主要介绍C#中通过Response.Headers设置自定义响应头的方法,涵盖基础添加、安全校验、生产实践及调试技巧,强... 目录一、基础设置方法1. 直接添加自定义头2. 批量设置模式二、高级配置技巧1. 安全校验机制2. 类型

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

C#实现高性能拍照与水印添加功能完整方案

《C#实现高性能拍照与水印添加功能完整方案》在工业检测、质量追溯等应用场景中,经常需要对产品进行拍照并添加相关信息水印,本文将详细介绍如何使用C#实现一个高性能的拍照和水印添加功能,包含完整的代码实现... 目录1. 概述2. 功能架构设计3. 核心代码实现python3.1 主拍照方法3.2 安全HBIT

C#实现SHP文件读取与地图显示的完整教程

《C#实现SHP文件读取与地图显示的完整教程》在地理信息系统(GIS)开发中,SHP文件是一种常见的矢量数据格式,本文将详细介绍如何使用C#读取SHP文件并实现地图显示功能,包括坐标转换、图形渲染、平... 目录概述功能特点核心代码解析1. 文件读取与初始化2. 坐标转换3. 图形绘制4. 地图交互功能缩放

C#使用SendMessage实现进程间通信的示例代码

《C#使用SendMessage实现进程间通信的示例代码》在软件开发中,进程间通信(IPC)是关键技术之一,C#通过调用WindowsAPI的SendMessage函数实现这一功能,本文将通过实例介绍... 目录第一章:SendMessage的底层原理揭秘第二章:构建跨进程通信桥梁2.1 定义通信协议2.2