DataExcel控件读取和保存excel xlsx 格式文件

news2024/11/23 22:23:29
需要引用NPOI库  https://github.com/dotnetcore/NPOI
调用Read 函数将excel读取到dataexcel控件
调用Save 函数将dataexcel控件文件保存为excel文件
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Feng.DataTool
{
    public class ExcelTools
    {
        public static void Save(Feng.Excel.DataExcel grid, string file)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
            List<CellStyleTemp> cellstyletemplist = new List<CellStyleTemp>();
            foreach (Feng.Excel.Interfaces.IRow gridrow in grid.Rows)
            {
                if (gridrow.Index < 1)
                    continue;
                IRow row = sheet1.CreateRow(gridrow.Index-1);
                row.Height = (short)(gridrow.Height * 20);
                foreach (Feng.Excel.Interfaces.IColumn column in grid.Columns)
                {
                    if (column.Index < 1)
                        continue;
                    
                    Feng.Excel.Interfaces.ICell gridcell = gridrow[column];
                    if (gridcell == null)
                        continue;
                    ushort width = (ushort)((column.Width) / 7 * 256);
                    sheet1.SetColumnWidth(column.Index-1, width);
                    ICell cell = row.CreateCell(column.Index-1);
                    string text = gridcell.Text;
                    cell.SetCellValue(text);

                    bool bottomlinestylevisible = false;
                    bool leftlinestylevisible = false;
                    bool rightlinestylevisible = false;
                    bool toplinestylevisible = false;
                    bool isstrikeout = false;
                    bool isbold = false;
                    double fontheightinpoints = 29;
                    string fontname = string.Empty;
                    if (gridcell.BorderStyle != null)
                    {
                        if (gridcell.BorderStyle.BottomLineStyle != null)
                        {
                            if (gridcell.BorderStyle.BottomLineStyle.Visible)
                            {
                                bottomlinestylevisible = true;
                            }
                        }
                        if (gridcell.BorderStyle.LeftLineStyle != null)
                        {
                            if (gridcell.BorderStyle.LeftLineStyle.Visible)
                            {
                                leftlinestylevisible = true;
                            }
                        }
                        if (gridcell.BorderStyle.RightLineStyle != null)
                        {
                            if (gridcell.BorderStyle.RightLineStyle.Visible)
                            {
                                rightlinestylevisible = true;
                            }
                        }
                        if (gridcell.BorderStyle.TopLineStyle != null)
                        {
                            if (gridcell.BorderStyle.TopLineStyle.Visible)
                            {
                                toplinestylevisible = true;
                            }
                        }
                    }

                    isstrikeout = gridcell.Font.Strikeout; 
                    isbold = gridcell.Font.Bold;
                    fontheightinpoints = gridcell.Font.Size;
                    fontname = gridcell.Font.Name;
                    int alignment = GetHAlignment(gridcell.HorizontalAlignment);
                    int verticalalignment = GetVAlignment(gridcell.VerticalAlignment);
                    ICellStyle style = GetCellStyle(hssfworkbook, cellstyletemplist
            , bottomlinestylevisible, leftlinestylevisible
            , rightlinestylevisible, toplinestylevisible
            , isstrikeout, isbold
            , fontheightinpoints, fontname
            , alignment, verticalalignment);
                    cell.CellStyle = style;
                }
            }


            foreach (Feng.Excel.Interfaces.IMergeCell item in grid.MergeCells)
            {
                sheet1.AddMergedRegion(new CellRangeAddress(item.MinCell.Row.Index-1,item.MaxRowIndex - 1, item.MinCell.Column.Index - 1, item.MaxColumnIndex - 1));
                //sheet1.AddMergedRegion(new CellRangeAddress(2, 7, 2, 7));
            }

            FileStream stream = new FileStream(file, FileMode.Create);
            hssfworkbook.Write(stream);
            stream.Close();
        }

        public static int GetHAlignment(StringAlignment alignment)
        {
            switch (alignment)
            {
                case StringAlignment.Near:
                    return 1; 
                case StringAlignment.Center:
                    return 2;
                case StringAlignment.Far:
                    return 3;
                default:
                    break;
            }
            return 0;
        }
        public static int GetVAlignment(StringAlignment alignment)
        {
            switch (alignment)
            {
                case StringAlignment.Near:
                    return 0;
                case StringAlignment.Center:
                    return 1;
                case StringAlignment.Far:
                    return 2;
                default:
                    break;
            }
            return 0;
        }
        public class CellStyleTemp
        {
            public CellStyleTemp()
            {
                
            }
            public bool BottomLineStyleVisible { get; set; }
            public bool LeftLineStyleVisible { get; set; }
            public bool RightLineStyleVisible { get; set; }
            public bool TopLineStyleVisible { get; set; }
            public bool IsStrikeout { get; set; }
            public bool IsBold { get; set; }
            public double FontHeightInPoints { get; set; }
            public string FontName { get; set; }
            public int Alignment { get; set; }
            public int VerticalAlignment { get; set; }

            public ICellStyle style { get; set; }
        }

        public static ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook, List<CellStyleTemp> styles
            , bool bottomlinestylevisible, bool leftlinestylevisible
            , bool rightlinestylevisible, bool toplinestylevisible
            , bool isstrikeout, bool isbold
            , double fontheightinpoints, string fontname
            , int alignment
            , int verticalalignment)
        { 
            foreach (CellStyleTemp item in styles)
            { 
                if (item.BottomLineStyleVisible != bottomlinestylevisible)
                {
                    continue;
                }
                double upfontheightinpoints = fontheightinpoints + 0.1;
                double downfontheightinpoints = fontheightinpoints - 0.1;
                if (!((item.FontHeightInPoints > downfontheightinpoints) && (item.FontHeightInPoints < upfontheightinpoints)))
                {
                    continue;
                }
                if (item.FontName != fontname)
                {
                    continue;
                }
                if (item.IsBold != isbold)
                {
                    continue;
                }
                if (item.IsStrikeout != isstrikeout)
                {
                    continue;
                }
                if (item.LeftLineStyleVisible != leftlinestylevisible)
                {
                    continue;
                }
                if (item.RightLineStyleVisible != rightlinestylevisible)
                {
                    continue;
                }
                if (item.TopLineStyleVisible != toplinestylevisible)
                {
                    continue;
                }
                if (item.Alignment != alignment)
                {
                    continue;
                }
                if (item.VerticalAlignment != verticalalignment)
                {
                    continue;
                }
                return item.style;
            }
            CellStyleTemp cellStyleTemp = new CellStyleTemp();
            cellStyleTemp.BottomLineStyleVisible = bottomlinestylevisible;
            cellStyleTemp.FontHeightInPoints = fontheightinpoints;
            cellStyleTemp.FontName = fontname;
            cellStyleTemp.IsBold = isbold;
            cellStyleTemp.IsStrikeout = isstrikeout;
            cellStyleTemp.LeftLineStyleVisible = leftlinestylevisible;
            cellStyleTemp.RightLineStyleVisible = rightlinestylevisible;
            cellStyleTemp.TopLineStyleVisible = toplinestylevisible;
            cellStyleTemp.Alignment = alignment;
            cellStyleTemp.VerticalAlignment = verticalalignment;
            ICellStyle style = CreateCellStyle(hssfworkbook
            , bottomlinestylevisible, leftlinestylevisible
            , rightlinestylevisible, toplinestylevisible
            , isstrikeout, isbold
            , fontheightinpoints, fontname, alignment
            , verticalalignment);
            cellStyleTemp.style = style;
            styles.Add(cellStyleTemp);
            return cellStyleTemp.style;
        }

        public static ICellStyle CreateCellStyle(HSSFWorkbook hssfworkbook
            , bool BottomLineStyleVisible, bool LeftLineStyleVisible
            , bool RightLineStyleVisible, bool TopLineStyleVisible
            , bool IsStrikeout, bool IsBold
            , double FontHeightInPoints, string FontName
            , int alignment
            , int verticalalignment)
        {
            ICellStyle style = hssfworkbook.CreateCellStyle();
            if (BottomLineStyleVisible)
            {
                style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            }
            if (LeftLineStyleVisible)
            {
                style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            }
            if (RightLineStyleVisible)
            {
                style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            }
            if (TopLineStyleVisible)
            {
                style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            }
             
            style.Alignment = (NPOI.SS.UserModel.HorizontalAlignment)alignment;
            style.VerticalAlignment = (NPOI.SS.UserModel.VerticalAlignment)verticalalignment;
            IFont font2 = hssfworkbook.CreateFont();
            font2.Color = HSSFColor.Black.Index;
            if (IsStrikeout)
            {
                font2.IsStrikeout = true;
            }
            if (IsBold)
            {
                font2.IsBold = true;
            }
            font2.FontHeightInPoints = FontHeightInPoints;
            font2.FontName = FontName;
            style.SetFont(font2);
            return style;
        }
        public static void Read(Feng.Excel.DataExcel grid, string file)
        {
            FileStream stream = new FileStream(file, FileMode.Open);
            HSSFWorkbook hssfworkbook = new HSSFWorkbook(stream);
            stream.Close();
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            int rowcount = sheet.LastRowNum;
            bool hassetcolumnwidth = false;
            for (int rowindex = 0; rowindex < rowcount; rowindex++)
            {
                IRow row = sheet.GetRow(rowindex);
                if (row == null)
                    continue;
                Feng.Excel.Interfaces.IRow gridrow = grid.GetRow(rowindex + 1);
                gridrow.Height = row.Height / 20;
                short columncount = row.LastCellNum;
                for (short columnindex = 0; columnindex < columncount; columnindex++)
                {
                    Feng.Excel.Interfaces.IColumn gridcolumn = grid.GetColumn(columnindex + 1);
                    int width = sheet.GetColumnWidth(columnindex); 
                    gridcolumn.Width = (width / 256) * 7;
                    ICell cell = row.GetCell(columnindex);
                    if (cell == null)
                        continue;
                    Feng.Excel.Interfaces.ICell gridcell = grid.GetCell(gridrow.Index, gridcolumn.Index);
                    gridcell.BorderStyle = new Excel.Styles.CellBorderStyle();
                    try
                    {
                        if (cell.CellType == CellType.String)
                        {
                            gridcell.Value = cell.StringCellValue;
                        }
                        if (cell.CellType == CellType.Numeric)
                        {
                            gridcell.Value = cell.NumericCellValue;
                        }
                        if (cell.CellType == CellType.Boolean)
                        {
                            gridcell.Value = cell.BooleanCellValue;
                        }
                        if (cell.CellType == CellType.Unknown)
                        {
                            gridcell.Value = cell.StringCellValue;
                        }

                        if (cell.CellStyle.BorderBottom == NPOI.SS.UserModel.BorderStyle.Thin)
                        {
                            gridcell.BorderStyle.BottomLineStyle = new Excel.Styles.LineStyle();
                            gridcell.BorderStyle.BottomLineStyle.Visible = true;
                        }
                        if (cell.CellStyle.BorderLeft == NPOI.SS.UserModel.BorderStyle.Thin)
                        {
                            gridcell.BorderStyle.LeftLineStyle = new Excel.Styles.LineStyle();
                            gridcell.BorderStyle.LeftLineStyle.Visible = true;

                        }
                        if (cell.CellStyle.BorderRight == NPOI.SS.UserModel.BorderStyle.Thin)
                        {
                            gridcell.BorderStyle.RightLineStyle = new Excel.Styles.LineStyle();
                            gridcell.BorderStyle.RightLineStyle.Visible = true;
                        }
                        if (cell.CellStyle.BorderTop == NPOI.SS.UserModel.BorderStyle.Thin)
                        {
                            gridcell.BorderStyle.TopLineStyle = new Excel.Styles.LineStyle();
                            gridcell.BorderStyle.TopLineStyle.Visible = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        Feng.Utils.TraceHelper.WriteTrace("SysTools", "ExcelTools", "Read", ex);
                    }
                    try
                    {
                        IFont font2 = cell.CellStyle.GetFont(hssfworkbook);
                        System.Drawing.FontStyle fontstyle = System.Drawing.FontStyle.Regular;
                        if (font2.IsStrikeout)
                        {
                            fontstyle = fontstyle | System.Drawing.FontStyle.Strikeout;
                        }
                        if (font2.IsBold)
                        {
                            fontstyle = fontstyle | System.Drawing.FontStyle.Bold;
                        }
                        font2.FontHeightInPoints = gridcell.Font.Size;
                        font2.FontName = gridcell.Font.Name;
                        gridcell.Font = new System.Drawing.Font(font2.FontName, (float)font2.FontHeightInPoints, fontstyle);
                    }
                    catch (Exception ex)
                    {
                        Feng.Utils.TraceHelper.WriteTrace("SysTools", "ExcelTools", "Read", ex);
                    }
                    try
                    {
                        if (cell.CellStyle.Alignment == NPOI.SS.UserModel.HorizontalAlignment.Center)
                        {
                            gridcell.HorizontalAlignment = StringAlignment.Center;
                        }
                        if (cell.CellStyle.Alignment == NPOI.SS.UserModel.HorizontalAlignment.Left)
                        {
                            gridcell.HorizontalAlignment = StringAlignment.Near;
                        }
                        if (cell.CellStyle.Alignment == NPOI.SS.UserModel.HorizontalAlignment.Right)
                        {
                            gridcell.HorizontalAlignment = StringAlignment.Far;
                        }
                    }
                    catch (Exception ex)
                    { 
                        Feng.Utils.TraceHelper.WriteTrace("SysTools", "ExcelTools", "Read", ex);
                    }
                    try
                    {
                        if (cell.CellStyle.VerticalAlignment == NPOI.SS.UserModel.VerticalAlignment.Center)
                        {
                            gridcell.VerticalAlignment = StringAlignment.Center;
                        }
                        if (cell.CellStyle.VerticalAlignment == NPOI.SS.UserModel.VerticalAlignment.Top)
                        {
                            gridcell.VerticalAlignment = StringAlignment.Near;
                        }
                        if (cell.CellStyle.VerticalAlignment == NPOI.SS.UserModel.VerticalAlignment.Bottom)
                        {
                            gridcell.VerticalAlignment = StringAlignment.Far;
                        }
                    }
                    catch (Exception ex)
                    {
                        Feng.Utils.TraceHelper.WriteTrace("SysTools", "ExcelTools", "Read", ex);
                    }
                }
            }

            List<CellRangeAddress> listmer = sheet.MergedRegions;
            if (listmer != null)
            {
                foreach (CellRangeAddress item in listmer)
                {
                    grid.MergeCell(item.FirstRow + 1, item.FirstColumn + 1, item.LastRow + 1, item.LastColumn + 1);
                }
            }
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1044392.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

pytho实例--pandas读取表格内容

前言&#xff1a;由于运维反馈帮忙计算云主机的费用&#xff0c;特编写此脚本进行运算 如图&#xff0c;有如下excel数据 计算过程中需用到数据库中的数据&#xff0c;故封装了一个读取数据库的类 import MySQLdb from sshtunnel import SSHTunnelForwarderclass SSHMySQL(ob…

Java BigDecimal 详解

目录 一、BigDecimal 1、简介 2、构造器描述 3、方法描述 4、使用 一、BigDecimal float和double类型的主要设计目标是为了科学计算和工程计算。他们执行二进制浮点运算&#xff0c;这是为了在广域数值范围上提供较为精确的快速近似计算而精心设计的。然而&#xff0c;它…

25841-2017 1000kV电力系统继电保护技术导则

声明 本文是学习GB-T 25841-2017 1000kV电力系统继电保护技术导则. 而整理的学习笔记,分享出来希望更多人受益,如果存在侵权请及时联系我们 1 范围 本标准规定了交流1000 kV 系统及1000 kV 变电站相关电压等级具有特别要求的继电保护装置 的基本准则。 本标准适用于1000 k…

大厂秋招真题【BFS+DP】华为20230921秋招T3-PCB印刷电路板布线【欧弟算法】全网最全大厂秋招题解

题目描述与示例 题目描述 在PCB印刷电路板设计中&#xff0c;器件之间的连线&#xff0c;要避免线路的阻抗值增大&#xff0c;而且器件之间还有别的器任和别的干扰源&#xff0c;在布线时我们希望受到的干扰尽量小。 现将电路板简化成一个M N的矩阵&#xff0c;每个位置&am…

如何快速学习AdsPower RPA(1)——简单、进阶部分

你是否刚开始学习使用AdsPower的RPA功能&#xff1f; 你是否对着这些操作选项头皮发麻&#xff0c;不知所措&#xff1f; 你是否想快速学会RPA&#xff1f; 你是否想编写出满足各种业务场景的RPA流程&#xff1f; 以上这些&#xff0c;Tool哥统统都帮你搞定&#xff01; Too…

科技成果鉴定测试有多重要?可出具专业测试报告的软件测评机构推荐

科技成果鉴定测试在现代社会中具有重要意义&#xff0c;它不仅可以评估科技成果的价值和可行性&#xff0c;还可以为科技创新提供决策依据&#xff0c;推动科技进步和社会发展&#xff0c;那么科技成果鉴定测试究竟重要在哪呢? 1、对于科技项目的投资决策至关重要。鉴定测试可…

YOLOV8-DET转ONNX和RKNN

目录 1. 前言 2.环境配置 (1) RK3588开发板Python环境 (2) PC转onnx和rknn的环境 3.PT模型转onnx 4. ONNX模型转RKNN 6.测试结果 1. 前言 yolov8就不介绍了&#xff0c;详细的请见YOLOV8详细对比&#xff0c;本文章注重实际的使用&#xff0c;从拿到yolov8的pt检测模型&…

玩转gpgpu-sim 04记—— __cudaRegisterBinary() of gpgpu-sim 到底做了什么

官方文档&#xff1a; GPGPU-Sim 3.x Manual __cudaRegisterBinary(void*) 被执行到的代码逻辑如下&#xff1a; void** CUDARTAPI __cudaRegisterFatBinary( void *fatCubin ) { #if (CUDART_VERSION < 2010)printf("GPGPU-Sim PTX: ERROR ** this version of GPGPU…

查看Linux系统信息的常用命令

文章目录 1. 机器配置查看2. 常用分析工具3. 常用指令解读3.1 lscpu 4. 定位僵尸进程5. 参考 1. 机器配置查看 # 总核数物理CPU个数x每颗物理CPU的核数 # 总逻辑CPU数物理CPU个数x每颗物理CPU的核数x超线程数 cat /proc/cpuinfo| grep "physical id"| sort| uniq| w…

电子电路学习笔记之NCV6324BMTAATBG——同步降压转换器

关于同步降压转换器&#xff1f; 是一种广泛应用于各种电子产品中的转换器。它具有输入范围宽、转换效率高、输出电流大等优点。在同步降压型转换器的驱动电路中&#xff0c;一般包括电平移位电路、死区时间控制电路以及过零检测电路等。 电平移位电路用于将固定电平Vcc和GND…

86、Redis 的 value 所支持的数据类型(String、List、Set、Zset、Hash)---->String相关命令

本次讲解要点&#xff1a; String相关命令&#xff1a;String是指value中的数据类型 启动redis服务器&#xff1a; 打开小黑窗&#xff1a; C:\Users\JH>e: E:>cd E:\install\Redis6.0\Redis-x64-6.0.14\bin E:\install\Redis6.0\Redis-x64-6.0.14\bin>redis-server.…

【知识点随笔分析】我看看谁还不会用CURL命令

目录 前言&#xff1a; CURL介绍&#xff1a; CURL的基本使用&#xff1a; CURL与PING命令的区别&#xff1a; CURL命令的应用&#xff1a; 总结&#xff1a; 前言&#xff1a; 当今互联网时代&#xff0c;与服务器进行数据交互成为了无法回避的需求。无论是获取Web…

电脑入门:电脑不认新硬盘时该怎么办?

电脑不认新硬盘时该怎么办? 当新硬盘加进后,正常工作时,没有什么问题。若电脑遇到特殊情况时,电脑对新硬盘“不认”,可采取以下措施让电脑重新“认”新硬盘,显示新分区(如G、H、I、J)。 咱的目的是保持S-ATA的开启,把控制板载S-ATA设定值由No变成Yes就可以。 首…

mysql 8.0.34 安装

1、进入mysql官网 &#xff1a;https://www.mysql.com/ 拉到最下面&#xff0c;选择社区服务 2、下载mysql服务 msi方式的参考&#xff1a;https://blog.csdn.net/m0_59086544/article/details/129034408。 这里介绍下zip格式的怎么使用&#xff01; 3、 安装服务 下载好 z…

使用Webpack设置TS引用模块,解决Module not found: Error: Can‘t resolve ‘./m1‘ in ...问题

当我们把ts文件作为模块被引用的时候&#xff0c;我们使用Webpack打包代码会报错&#xff1a; Module not found: Error: Cant resolve ./m1 in ... 解决方法&#xff1a; 在webpack.config.js文件中配置如下代码&#xff1a; module.exports {// 设置引用模块resolve: {ext…

React 全栈体系(十七)

第九章 React Router 6 一、概述 React Router 以三个不同的包发布到 npm 上&#xff0c;它们分别为&#xff1a; react-router: 路由的核心库&#xff0c;提供了很多的&#xff1a;组件、钩子。react-router-dom: 包含 react-router 所有内容&#xff0c;并添加一些专门用于 …

解决oss视频上传后截取的第一帧图片被旋转问题

因此,直接配置参数ar_auto就okpic.url ?x-oss-processvideo/snapshot,t_1000,m_fast,ar_auto

Unity Game FrameWork—模块使用—资源热更新

工程选项配置​ json文件解析不要用默认的unity解析方式&#xff0c;unity解析有问题&#xff0c;使用StarForce.LitJsonHelper​ ​ 资源模式改为热更新模式​ ​ 配置文件配置​ BuiltinDataComponent自定义组件引用率了Buildinfo.txt配置文件&#xff0c;该文件配置了热更…

根据excel批量修改文件夹及其文件名称

简介 表哥公司电脑上有一大批文件夹&#xff0c;用于存放一些pdf。他希望对这些文件进行整理。文件夹批量重命名为好记一些的名字&#xff0c;文件夹下的pdf改成的名字格式为&#xff1a;文件夹名序号。 例如&#xff1a;文件夹从“1234”&#xff0c;改成“案件001”&#xf…

Sql注入(手工注入思路、绕过、防御)

一、Sql注入思路 1、判断注入点 在GET参数、POST参数、以及HTTP头部等&#xff0c;包括Cookie、Referer、XFF(X-Forwarded-for)、UA等地方尝试插入代码、符号或语句&#xff0c;尝试是否存在数据库参数读取行为&#xff0c;以及能否对其参数产生影响&#xff0c;如产生影响则…