LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C# 借助NPOI 完成 xls 转换为xlsx,而不安装MICROSOFT OFFICE?

admin
2023年12月30日 0:39 本文热度 452

背景:MinExcel开类库,导数据的库,占用内存很低,通过io,不通过内存保存,不支持 xls格式的文件,支持csv和xlsx,所以要想使用这个库,就得把xls格式转换为xlsx。只复制了数据 合并单元格,没复制格式这些。

  1. public string ConvertToXlsx(string xlsPath, string newExcelPath)

  2.        {

  3.            VAR oldWorkBook = new HSSFWorkbook(new FileStream(xlsPath, FileMode.OPEn));

  4.            var oldWorkSheet = oldWorkbook.GetSheetAt(0);

  5.            int m = 0;

  6.            try

  7.            {

  8.                using (var fileStream = new FileStream(newExcelPath, FileMode.Create))

  9.                {

  10.                    var newWorkBook = new XSSFWorkbook();

  11.                    var newWorkSheet = newWorkBook.CreateSheet("Sheet1");

  12.                    int i = 0;

  13.                    foreach (HSSFRow oldRow in oldWorkSheet)

  14.                    {

  15.                        var newRow = newWorkSheet.CreateRow(oldRow.RowNum);

  16.                        for (int ii = oldRow.FirstCellNum; ii < oldRow.Cells.Count; ii++)

  17.                        {

  18.                            m = ii;

  19.                            var newCell = newRow.CreateCell(ii);

  20.                            newCell.SetCellValue(GetValueType(oldRow.Cells[ii]).ToString());

  21.                        }

  22.                    }

  23.                    int sheetMergerCount = oldWorkSheet.NumMergedRegions;

  24.                    for (int me = 0; me < sheetMergerCount; me++)

  25.                        newWorkSheet.AddMergedRegion(oldWorkSheet.GetMergedRegion(me));

  26.                    newWorkBook.WrITe(fileStream);

  27.                    newWorkBook.Close();

  28.                }

  29.            }

  30.            catch (Exception ex)

  31.            {

  32.                int b = m;

  33.                throw;

  34.            }

  35.            oldWorkbook.Close();

  36.            return newExcelPath;

网上找的一个更完善的用法,带格式:

  1. using NPOI.SS.UserModel;

  2. using System;

  3. using System.Collections.Generic;

  4. using System.Linq;

  5. using System.Text;

  6. using System.Threading.Tasks;

  7. namespace FixturedataimportFromExcel.COMmon

  8. {

  9.    public static class NPOIExt

  10.    {

  11.        /// <summary>

  12.        /// 跨工作薄Workbook复制工作表Sheet

  13.        /// </summary>

  14.        /// <param name="sSheet">源工作表Sheet</param>

  15.        /// <param name="dWb">目标工作薄Workbook</param>

  16.        /// <param name="dSheetName">目标工作表Sheet名</param>

  17.        /// <param name="clonePRintSETUP">是否复制打印设置</param>

  18.        public static ISheet CrossCloneSheet(this ISheet sSheet, IWorkbook dWb, string dSheetName, bool clonePrintSetup)

  19.        {

  20.            ISheet dSheet;

  21.            dSheetName = string.IsNullOrEmpty(dSheetName) ? sSheet.SheetName : dSheetName;

  22.            dSheetName = (dWb.GetSheet(dSheetName) == null) ? dSheetName : dSheetName + "_拷贝";

  23.            dSheet = dWb.GetSheet(dSheetName) ?? dWb.CreateSheet(dSheetName);

  24.            CopySheet(sSheet, dSheet);

  25.            if (clonePrintSetup)

  26.                ClonePrintSetup(sSheet, dSheet);

  27.            dWb.SetActiveSheet(dWb.GetSheetIndex(dSheet));  //当前Sheet作为下次打开默认Sheet

  28.            return dSheet;

  29.        }

  30.        /// <summary>

  31.        /// 跨工作薄Workbook复制工作表Sheet

  32.        /// </summary>

  33.        /// <param name="sSheet">源工作表Sheet</param>

  34.        /// <param name="dWb">目标工作薄Workbook</param>

  35.        /// <param name="dSheetName">目标工作表Sheet名</param>

  36.        public static ISheet CrossCloneSheet(this ISheet sSheet, IWorkbook dWb, string dSheetName)

  37.        {

  38.            bool clonePrintSetup = true;

  39.            return CrossCloneSheet(sSheet, dWb, dSheetName, clonePrintSetup);

  40.        }

  41.        /// <summary>

  42.        /// 跨工作薄Workbook复制工作表Sheet

  43.        /// </summary>

  44.        /// <param name="sSheet">源工作表Sheet</param>

  45.        /// <param name="dWb">目标工作薄Workbook</param>

  46.        public static ISheet CrossCloneSheet(this ISheet sSheet, IWorkbook dWb)

  47.        {

  48.            string dSheetName = sSheet.SheetName;

  49.            bool clonePrintSetup = true;

  50.            return CrossCloneSheet(sSheet, dWb, dSheetName, clonePrintSetup);

  51.        }

  52.        private static IFont FinDFont(this IWorkbook dWb, IFont font, List<IFont> dFonts)

  53.        {

  54.            //IFont dFont = dWb.FindFont(font.Boldweight, font.Color, (short)font.FontHeight, font.FontName, font.IsItalic, font.IsStrikeout, font.TypeOffset, font.Underline);

  55.            IFont dFont = null;

  56.            foreach (IFont currFont in dFonts)

  57.            {

  58.                //if (currFont.Charset != font.Charset) continue;

  59.                //else

  60.                //if (currFont.Color != font.Color) continue;

  61.                //else

  62.                if (currFont.FontName != font.FontName) continue;

  63.                else if (currFont.FontHeight != font.FontHeight) continue;

  64.                else if (currFont.IsBold != font.IsBold) continue;

  65.                else if (currFont.IsItalic != font.IsItalic) continue;

  66.                else if (currFont.IsStrikeout != font.IsStrikeout) continue;

  67.                else if (currFont.Underline != font.Underline) continue;

  68.                else if (currFont.TypeOffset != font.TypeOffset) continue;

  69.                else { dFont = currFont; break; }

  70.            }

  71.            return dFont;

  72.        }

  73.        private static ICellStyle FindStyle(this IWorkbook dWb, IWorkbook sWb, ICellStyle style, List<ICellStyle> dCellStyles, List<IFont> dFonts)

  74.        {

  75.            ICellStyle dStyle = null;

  76.            foreach (ICellStyle currStyle in dCellStyles)

  77.            {

  78.                if (currStyle.Alignment != style.Alignment) continue;

  79.                else if (currStyle.VerticalAlignment != style.VerticalAlignment) continue;

  80.                else if (currStyle.BorderTop != style.BorderTop) continue;

  81.                else if (currStyle.BorderBottom != style.BorderBottom) continue;

  82.                else if (currStyle.BorderLeft != style.BorderLeft) continue;

  83.                else if (currStyle.BorderRight != style.BorderRight) continue;

  84.                else if (currStyle.TopBorderColor != style.TopBorderColor) continue;

  85.                else if (currStyle.BottomBorderColor != style.BottomBorderColor) continue;

  86.                else if (currStyle.LeftBorderColor != style.LeftBorderColor) continue;

  87.                else if (currStyle.RightBorderColor != style.RightBorderColor) continue;

  88.                //else if (currStyle.BorderDiagonal != style.BorderDiagonal) continue;

  89.                //else if (currStyle.BorderDiagonalColor != style.BorderDiagonalColor) continue;

  90.                //else if (currStyle.BorderDiagonalLineStyle != style.BorderDiagonalLineStyle) continue;

  91.                //else if (currStyle.FillBackgroundColor != style.FillBackgroundColor) continue;

  92.                //else if (currStyle.FillBackgroundColorColor != style.FillBackgroundColorColor) continue;

  93.                //else if (currStyle.FillForegroundColor != style.FillForegroundColor) continue;

  94.                //else if (currStyle.FillForegroundColorColor != style.FillForegroundColorColor) continue;

  95.                //else if (currStyle.FillPattern != style.FillPattern) continue;

  96.                else if (currStyle.Indention != style.Indention) continue;

  97.                else if (currStyle.IsHidden != style.IsHidden) continue;

  98.                else if (currStyle.IsLocked != style.IsLocked) continue;

  99.                else if (currStyle.Rotation != style.Rotation) continue;

  100.                else if (currStyle.ShrinkToFit != style.ShrinkToFit) continue;

  101.                else if (currStyle.WrapText != style.WrapText) continue;

  102.                else if (!currStyle.GetDataFormatString().Equals(style.GetDataFormatString())) continue;

  103.                else

  104.                {

  105.                    IFont sFont = sWb.GetFontAt(style.FontIndex);

  106.                    IFont dFont = dWb.FindFont(sFont, dFonts);

  107.                    if (dFont == null) continue;

  108.                    else

  109.                    {

  110.                        currStyle.SetFont(dFont);

  111.                        dStyle = currStyle;

  112.                        break;

  113.                    }

  114.                }

  115.            }

  116.            return dStyle;

  117.        }

  118.        private static IFont CopyFont(this IFont dFont, IFont sFont, List<IFont> dFonts)

  119.        {

  120.            //dFont.Charset = sFont.Charset;

  121.            //dFont.Color = sFont.Color;

  122.            dFont.FontHeight = sFont.FontHeight;

  123.            dFont.FontName = sFont.FontName;

  124.            dFont.IsBold = sFont.IsBold;

  125.            dFont.IsItalic = sFont.IsItalic;

  126.            dFont.IsStrikeout = sFont.IsStrikeout;

  127.            dFont.Underline = sFont.Underline;

  128.            dFont.TypeOffset = sFont.TypeOffset;

  129.            dFonts.Add(dFont);

  130.            return dFont;

  131.        }

  132.        private static ICellStyle CopyStyle(this ICellStyle dCellStyle, ICellStyle sCellStyle, IWorkbook dWb, IWorkbook sWb, List<ICellStyle> dCellStyles, List<IFont> dFonts)

  133.        {

  134.            ICellStyle currCellStyle = dCellStyle;

  135.            currCellStyle.Alignment = sCellStyle.Alignment;

  136.            currCellStyle.VerticalAlignment = sCellStyle.VerticalAlignment;

  137.            currCellStyle.BorderTop = sCellStyle.BorderTop;

  138.            currCellStyle.BorderBottom = sCellStyle.BorderBottom;

  139.            currCellStyle.BorderLeft = sCellStyle.BorderLeft;

  140.            currCellStyle.BorderRight = sCellStyle.BorderRight;

  141.            currCellStyle.TopBorderColor = sCellStyle.TopBorderColor;

  142.            currCellStyle.LeftBorderColor = sCellStyle.LeftBorderColor;

  143.            currCellStyle.RightBorderColor = sCellStyle.RightBorderColor;

  144.            currCellStyle.BottomBorderColor = sCellStyle.BottomBorderColor;

  145.            //dCellStyle.BorderDiagonal = sCellStyle.BorderDiagonal;

  146.            //dCellStyle.BorderDiagonalColor = sCellStyle.BorderDiagonalColor;

  147.            //dCellStyle.BorderDiagonalLineStyle = sCellStyle.BorderDiagonalLineStyle;

  148.            //dCellStyle.FillBackgroundColor = sCellStyle.FillBackgroundColor;

  149.            dCellStyle.FillForegroundColor = sCellStyle.FillForegroundColor;

  150.            //dCellStyle.FillPattern = sCellStyle.FillPattern;

  151.            currCellStyle.Indention = sCellStyle.Indention;

  152.            currCellStyle.IsHidden = sCellStyle.IsHidden;

  153.            currCellStyle.IsLocked = sCellStyle.IsLocked;

  154.            currCellStyle.Rotation = sCellStyle.Rotation;

  155.            currCellStyle.ShrinkToFit = sCellStyle.ShrinkToFit;

  156.            currCellStyle.WrapText = sCellStyle.WrapText;

  157.            currCellStyle.DataFormat = dWb.CreateDataFormat().GetFormat(sWb.CreateDataFormat().GetFormat(sCellStyle.DataFormat));

  158.            IFont sFont = sCellStyle.GetFont(sWb);

  159.            IFont dFont = dWb.FindFont(sFont, dFonts) ?? dWb.CreateFont().CopyFont(sFont, dFonts);

  160.            currCellStyle.SetFont(dFont);

  161.            dCellStyles.Add(currCellStyle);

  162.            return currCellStyle;

  163.        }

  164.        private static void CopySheet(ISheet sSheet, ISheet dSheet)

  165.        {

  166.            var maxColumnNum = 0;

  167.            List<ICellStyle> dCellStyles = new List<ICellStyle>();

  168.            List<IFont> dFonts = new List<IFont>();

  169.            MergerRegion(sSheet, dSheet);

  170.            for (int i = sSheet.FirstRowNum; i <= sSheet.LastRowNum; i++)

  171.            {

  172.                IRow sRow = sSheet.GetRow(i);

  173.                IRow dRow = dSheet.CreateRow(i);

  174.                if (sRow != null)

  175.                {

  176.                    CopyRow(sRow, dRow, dCellStyles, dFonts);

  177.                    if (sRow.LastCellNum > maxColumnNum)

  178.                        maxColumnNum = sRow.LastCellNum;

  179.                }

  180.            }

  181.            for (int i = 0; i <= maxColumnNum; i++)

  182.                dSheet.SetColumnWidth(i, sSheet.GetColumnWidth(i));

  183.        }

  184.        private static void CopyRow(IRow sRow, IRow dRow, List<ICellStyle> dCellStyles, List<IFont> dFonts)

  185.        {

  186.            dRow.Height = sRow.Height;

  187.            ISheet sSheet = sRow.Sheet;

  188.            ISheet dSheet = dRow.Sheet;

  189.            for (int j = sRow.FirstCellNum; j <= sRow.LastCellNum; j++)

  190.            {

  191.                NPOI.SS.UserModel.ICell sCell = sRow.GetCell(j);

  192.                NPOI.SS.UserModel.ICell dCell = dRow.GetCell(j);

  193.                if (sCell != null)

  194.                {

  195.                    if (dCell == null)

  196.                        dCell = dRow.CreateCell(j);

  197.                    CopyCell(sCell, dCell, dCellStyles, dFonts);

  198.                }

  199.            }

  200.        }

  201.        private static void CopyCell(NPOI.SS.UserModel.ICell sCell, NPOI.SS.UserModel.ICell dCell, List<ICellStyle> dCellStyles, List<IFont> dFonts)

  202.        {

  203.            ICellStyle currCellStyle = dCell.Sheet.Workbook.FindStyle(sCell.Sheet.Workbook, sCell.CellStyle, dCellStyles, dFonts);

  204.            if (currCellStyle == null)

  205.                currCellStyle = dCell.Sheet.Workbook.CreateCellStyle().CopyStyle(sCell.CellStyle, dCell.Sheet.Workbook, sCell.Sheet.Workbook, dCellStyles, dFonts);

  206.            dCell.CellStyle = currCellStyle;

  207.            switch (sCell.CellType)

  208.            {

  209.                case CellType.String:

  210.                    dCell.SetCellValue(sCell.StrinGCEllValue);

  211.                    break;

  212.                case CellType.Numeric:

  213.                    dCell.SetCellValue(sCell.NumericCellValue);

  214.                    break;

  215.                case CellType.Blank:

  216.                    dCell.SetCellType(CellType.Blank);

  217.                    break;

  218.                case CellType.Boolean:

  219.                    dCell.SetCellValue(sCell.BooleanCellValue);

  220.                    break;

  221.                case CellType.Error:

  222.                    dCell.SetCellValue(sCell.ErrorCellValue);

  223.                    break;

  224.                case CellType.Formula:

  225.                    dCell.SetCellFormula(sCell.CellFormula);

  226.                    break;

  227.                default:

  228.                    break;

  229.            }

  230.        }

  231.        private static void MergerRegion(ISheet sSheet, ISheet dSheet)

  232.        {

  233.            int sheetMergerCount = sSheet.NumMergedRegions;

  234.            for (int i = 0; i < sheetMergerCount; i++)

  235.                dSheet.AddMergedRegion(sSheet.GetMergedRegion(i));

  236.        }

  237.        private static void ClonePrintSetup(ISheet sSheet, ISheet dSheet)

  238.        {

  239.            //工作表Sheet页面打印设置

  240.            dSheet.PrintSetup.Copies = 1;                               //打印份数

  241.            dSheet.PrintSetup.PaperSize = sSheet.PrintSetup.PaperSize;  //纸张大小

  242.            dSheet.PrintSetup.Landscape = sSheet.PrintSetup.Landscape;  //纸张方向:默认纵向false(横向true)

  243.            dSheet.PrintSetup.Scale = sSheet.PrintSetup.Scale;          //缩放方式比例

  244.            dSheet.PrintSetup.FitHeight = sSheet.PrintSetup.FitHeight;  //调整方式页高

  245.            dSheet.PrintSetup.FitWidth = sSheet.PrintSetup.FitWidth;    //调整方式页

  246.            dSheet.PrintSetup.FooterMargin = sSheet.PrintSetup.FooterMargin;

  247.            dSheet.PrintSetup.HeaderMargin = sSheet.PrintSetup.HeaderMargin;

  248.            //边距

  249.            dSheet.SetMargin(MarginType.TopMargin, sSheet.GetMargin(MarginType.TopMargin));

  250.            dSheet.SetMargin(MarginType.BottomMargin, sSheet.GetMargin(MarginType.BottomMargin));

  251.            dSheet.SetMargin(MarginType.LeftMargin, sSheet.GetMargin(MarginType.LeftMargin));

  252.            dSheet.SetMargin(MarginType.RightMargin, sSheet.GetMargin(MarginType.RightMargin));

  253.            dSheet.SetMargin(MarginType.HeaderMargin, sSheet.GetMargin(MarginType.HeaderMargin));

  254.            dSheet.SetMargin(MarginType.FooterMargin, sSheet.GetMargin(MarginType.FooterMargin));

  255.            //页眉页脚

  256.            dSheet.Header.Left = sSheet.Header.Left;

  257.            dSheet.Header.center = sSheet.Header.Center;

  258.            dSheet.Header.Right = sSheet.Header.Right;

  259.            dSheet.Footer.Left = sSheet.Footer.Left;

  260.            dSheet.Footer.Center = sSheet.Footer.Center;

  261.            dSheet.Footer.Right = sSheet.Footer.Right;

  262.            //工作表Sheet参数设置

  263.            dSheet.IsPrintGridlines = sSheet.IsPrintGridlines;          //true: 打印整表网格线。不单独设置CellStyle时外框实线内框虚线。 false: 自己设置网格线

  264.            dSheet.FitToPage = sSheet.FitToPage;                        //自适应页面

  265.            dSheet.HorizontallyCenter = sSheet.HorizontallyCenter;      //打印页面为水平居中

  266.            dSheet.VerticallyCenter = sSheet.VerticallyCenter;          //打印页面为垂直居中

  267.            dSheet.RepeatingRows = sSheet.RepeatingRows;                //工作表顶端标题行范围

  268.        }

  269.    }

  270. }

View Code

使用:

  1. using (var fileStream = new FileStream(newExcelPath, FileMode.Create))

  2. {

  3.       var newWorkBook1 = new XSSFWorkbook();

  4.       var sheet = oldWorkSheet.CrossCloneSheet(newWorkBook1, "Sheet1");

  5.       newWorkBook1.Add(sheet);

  6.       newWorkBook1.Write(fileStream);

  7.       newWorkBook1.Close();

  8. }

  9. oldWorkbook.Close();

大部分格式都得行。


这个类的原文地址:C# NPOI Excel 跨工作薄Workbook复制工作表Sheet

该文章在 2023/12/30 0:39:16 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved