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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

oracle 11g导入\导出(expdp impdp)之导入过程

《oracle11g导入导出(expdpimpdp)之导入过程》导出需使用SEC.DMP格式,无分号;建立expdir目录(E:/exp)并确保存在;导入在cmd下执行,需sys用户权限;若需修... 目录准备文件导入(impdp)1、建立directory2、导入语句 3、更改密码总结上一个环节,我们讲了

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

C#文件复制异常:"未能找到文件"的解决方案与预防措施

《C#文件复制异常:未能找到文件的解决方案与预防措施》在C#开发中,文件操作是基础中的基础,但有时最基础的File.Copy()方法也会抛出令人困惑的异常,当targetFilePath设置为D:2... 目录一个看似简单的文件操作问题问题重现与错误分析错误代码示例错误信息根本原因分析全面解决方案1. 确保

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

C#高效实现Word文档内容查找与替换的6种方法

《C#高效实现Word文档内容查找与替换的6种方法》在日常文档处理工作中,尤其是面对大型Word文档时,手动查找、替换文本往往既耗时又容易出错,本文整理了C#查找与替换Word内容的6种方法,大家可以... 目录环境准备方法一:查找文本并替换为新文本方法二:使用正则表达式查找并替换文本方法三:将文本替换为图