【.Net 6.0--通用帮助类--ExcelHelper】

本文介绍了如何使用Aspose.Cells库在.NET中进行Excel文件的读写操作,包括将DataTable转换为Excel,合并单元格,以及设置单元格下拉列表。提供代码示例展示了如何实现这些功能,无需安装完整的Office环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

返回首页

前言

Excel帮助类,无需安装office即可使用,包含了读取excel到datatable(ExcelToDataTable)、保存datatable到excel(DataTableToExcel)、设置单元格枚举值(SetCellList)、合并单元格(SetCellMerge)等方法。

需要引用Aspose.Cells,依赖文件,我已共享资源,请需要的同学自行下载。


代码示例

using Aspose.Cells;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace VW.API.Common.Utils
{
    /// <summary>
    /// 合并单元格实体类
    /// </summary>
    public class CellMergeModel
    {
        /// <summary>
        /// 开始行
        /// </summary>
        public int FirstRow { set; get; }
        /// <summary>
        /// 开始列
        /// </summary>
        public int FirstColumn { set; get; }
        /// <summary>
        /// 合并行数
        /// </summary>
        public int TotalRows { set; get; }
        /// <summary>
        /// 合并列数
        /// </summary>
        public int TotalColumns { set; get; }
    }

    /// <summary>
    /// 单元格下拉实体类
    /// </summary>
    public class CellListModel
    {
        /// <summary>
        /// 开始行
        /// </summary>
        public int StartRow { set; get; }
        /// <summary>
        /// 开始列
        /// </summary>
        public int StartColumn { set; get; }
        /// <summary>
        /// 结束行
        /// </summary>
        public int EndRow { set; get; }
        /// <summary>
        /// 结束列
        /// </summary>
        public int EndColumn { set; get; }
        /// <summary>
        /// list
        /// </summary>
        public string Formula1 { set; get; }
    }

    /// <summary>
    /// ExcelHelper 的摘要说明:Excel帮助类
    /// </summary>
    public static class ExcelHelper
    {
        /// <summary>
        /// 合并单元格
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="mergeModels">合并单元格参数</param>
        /// <param name="sheetIndex">sheet序号</param>
        /// <returns></returns>
        public static bool SetCellMerge(string filePath, List<CellMergeModel> mergeModels, int sheetIndex = 0)
        {
            try
            {
                Workbook book = new Workbook(filePath);
                Cells cells = book.Worksheets[sheetIndex].Cells;

                foreach (CellMergeModel mergeModel in mergeModels)
                {
                    cells.Merge(mergeModel.FirstRow, mergeModel.FirstColumn, mergeModel.TotalRows, mergeModel.TotalColumns);
                }

                book.Save(filePath);

                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// List单元格
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="cellListModels">List单元格参数</param>
        /// <param name="sheetIndex">sheet序号</param>
        /// <returns></returns>
        public static bool SetCellList(string filePath, List<CellListModel> cellListModels, int sheetIndex = 0)
        {
            try
            {
                Workbook workbook = new Workbook(filePath);
                Worksheet worksheet = workbook.Worksheets[sheetIndex];

                ValidationCollection validations = worksheet.Validations;
                foreach (CellListModel cellListModel in cellListModels)
                {
                    CellArea area = new CellArea
                    {
                        StartRow = cellListModel.StartRow,
                        EndRow = cellListModel.EndRow,
                        StartColumn = cellListModel.StartColumn,
                        EndColumn = cellListModel.EndColumn
                    };

                    Validation validation = validations[validations.Add(area)];
                    validation.Type = ValidationType.List;
                    validation.Operator = OperatorType.None;
                    validation.InCellDropDown = true;
                    validation.Formula1 = cellListModel.Formula1;
                    validation.ShowError = true;
                    validation.AlertStyle = ValidationAlertType.Stop;
                    validation.ErrorTitle = "错误";
                    validation.ErrorMessage = "请从列表中选择一项";
                }

                workbook.Save(filePath);

                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private static DataTable ExcelToDataTable(Workbook workbook,
            int sheet = 0,
            int firstRow = 0,
            int firstColumn = 0,
            bool showTitle = true)
        {
            Cells cells = workbook.Worksheets[sheet].Cells;
            //excel->datatable
            DataTable dataTable = cells.ExportDataTableAsString(firstRow, firstColumn, cells.MaxDataRow + 1, cells.MaxColumn + 1, showTitle);

            //获取合并单元格
            ArrayList arrayLists = cells.MergedCells;
            foreach (CellArea item in arrayLists)
            {
                if (item.StartRow < firstRow)
                    continue;
                for (int i = item.StartRow - firstRow; i <= item.EndRow - firstRow; i++)
                {
                    for (int j = item.StartColumn; j <= item.EndColumn; j++)
                    {
                        if (item.StartColumn == item.EndColumn)//合并行
                            dataTable.Rows[i][j] = dataTable.Rows[item.StartRow - firstRow][item.StartColumn];
                    }
                }
            }

            return dataTable;
        }

        /// <summary>
        /// excel-datatable
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="sheetIndex">sheet序号</param>
        /// <param name="firstRow">开始行</param>
        /// <param name="firstColumn">开始列</param>
        /// <param name="showTitle">是否显示列名(如果多维表头,设置为false,否则列名显示有问题,无法绑定到dataview显示)</param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(string filePath,
            int sheetIndex = 0,
            int firstRow = 0,
            int firstColumn = 0,
            bool showTitle = true)
        {
            try
            {
                Workbook workbook = new Workbook(filePath);

                return ExcelToDataTable(workbook, sheetIndex, firstRow, firstColumn, showTitle);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// excel-datatable
        /// </summary>
        /// <param name="stream">文件Steam</param>
        /// <param name="sheetIndex">sheet序号</param>
        /// <param name="firstRow">开始行</param>
        /// <param name="firstColumn">开始列</param>
        /// <param name="showTitle">是否显示列名</param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(Stream stream,
            int sheetIndex = 0,
            int firstRow = 0,
            int firstColumn = 0,
            bool showTitle = true)
        {
            try
            {
                Workbook workbook = new Workbook(stream);

                return ExcelToDataTable(workbook, sheetIndex, firstRow, firstColumn, showTitle);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// datatable->excel(普通导出)
        /// </summary>
        /// <param name="dtData">导出数据</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static bool DataTableToExcel(DataTable dtData, string filePath, int sheetIndex = 0, string sheetName = "默认sheet")
        {
            try
            {
                Workbook book = sheetIndex != 0 ? new Workbook(filePath) : new Workbook();
                Worksheet sheet = sheetIndex != 0 && book.Worksheets.Count <= sheetIndex ? book.Worksheets.Add(sheetName) : book.Worksheets[sheetIndex];
                sheet.Cells.Clear();
                Cells cells = sheet.Cells;
                int Colnum = dtData.Columns.Count; // 表格列数 
                int Rownum = dtData.Rows.Count; // 表格行数 
                // 生成行 列名行 
                for (int i = 0; i < Colnum; i++)
                {
                    cells[0, i].PutValue(dtData.Columns[i].ColumnName); // 添加表头
                }
                // 生成数据行 
                for (int i = 0; i < Rownum; i++)
                {
                    for (int k = 0; k < Colnum; k++)
                    {
                        cells[1 + i, k].PutValue(dtData.Rows[i][k].ToString()); // 添加数据
                    }
                }
                sheet.AutoFitColumns(); // 自适应宽
                book.Save(filePath);

                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// datatable->excel(模板导出)
        /// </summary>
        /// <param name="dtData">导出数据</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="sheetIndex">sheet序号</param>
        /// <param name="excelStartRow">excel开始行</param>
        /// <param name="dataTableStartRow">datatable开始行</param>
        /// <param name="dataTableEndRow">datatable结束行</param>
        /// <returns></returns>
        public static bool DataTableToExcelByTemplate(DataTable dtData,
            string filePath,
            int sheetIndex = 0,
            int excelStartRow = 0,
            int dataTableStartRow = 0,
            int dataTableEndRow = 0)
        {
            try
            {
                Workbook book = new Workbook(filePath);
                Cells cells = book.Worksheets[sheetIndex].Cells;

                for (int i = dataTableStartRow; i <= dataTableEndRow; i++)
                {
                    //插入行
                    cells.InsertRow(excelStartRow + i);

                    for (int k = 0; k < dtData.Columns.Count; k++)
                    {
                        cells[excelStartRow + i, k].PutValue(dtData.Rows[i][k].ToString());
                        //取开始行的单元格样式,并且赋值给当前单元格
                        cells[excelStartRow + i, k].SetStyle(cells[excelStartRow - 1, k].GetStyle());
                    }
                }

                book.Save(filePath);

                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丿Nohedid灬山羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值