Example #1
0
        public void TestDataStyle()

        {
            string filepath = TempFile.GetTempFilePath("TestWriteSheetStyleDate",
                                                       ".xls");
            FileStream   out1 = new FileStream(filepath, FileMode.OpenOrCreate);
            HSSFWorkbook wb   = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet     s  = wb.CreateSheet();
            NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();
            IRow row = s.CreateRow(0);

            // with Date:
            ICell cell = row.CreateCell(1);

            cs.DataFormat  = (HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
            cell.CellStyle = (cs);
            cell.SetCellValue(DateTime.Now);

            // with Calendar:
            cell           = row.CreateCell(2);
            cs.DataFormat  = (HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
            cell.CellStyle = (cs);
            cell.SetCellValue(DateTime.Now);

            wb.Write(out1);
            out1.Close();
            SanityChecker sanityChecker = new SanityChecker();

            sanityChecker.CheckHSSFWorkbook(wb);

            Assert.AreEqual(0, s.LastRowNum, "LAST ROW ");
            Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW ");
        }
Example #2
0
        /// <summary>
        /// 插入数据行
        /// </summary>
        protected static void InsertRow(DataTable dtSource, HSSFWorkbook excelWorkbook)
        {
            int rowCount   = 0;
            int sheetCount = 1;

            NPOI.SS.UserModel.ISheet newsheet = null;

            //循环数据源导出数据集
            newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
            CreateHeader(newsheet, excelWorkbook);

            #region 样式声明
            //格式化显示
            NPOI.SS.UserModel.ICellStyle  cellStyle_DateTime = excelWorkbook.CreateCellStyle();
            NPOI.SS.UserModel.IDataFormat format             = excelWorkbook.CreateDataFormat();
            cellStyle_DateTime.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss");
            #endregion

            foreach (DataRow dr in dtSource.Rows)
            {
                rowCount++;
                //超出10000条数据 创建新的工作簿
                if (rowCount == 5000)
                {
                    rowCount = 1;
                    sheetCount++;
                    newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
                    CreateHeader(newsheet, excelWorkbook);
                }

                NPOI.SS.UserModel.IRow newRow = newsheet.CreateRow(rowCount);
                InsertCell(dtSource, dr, newRow, newsheet, excelWorkbook, cellStyle_DateTime);
            }
        }
Example #3
0
        public void TestCloneStyleSameWB()
        {
            HSSFWorkbook wb  = new HSSFWorkbook();
            IFont        fnt = wb.CreateFont();

            fnt.FontName = ("TestingFont");
            Assert.AreEqual(5, wb.NumberOfFonts);

            NPOI.SS.UserModel.ICellStyle orig = wb.CreateCellStyle();
            orig.Alignment = (HorizontalAlignment.Right);
            orig.SetFont(fnt);
            orig.DataFormat = ((short)18);

            Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment);
            Assert.AreEqual(fnt, orig.GetFont(wb));
            Assert.AreEqual(18, orig.DataFormat);

            NPOI.SS.UserModel.ICellStyle clone = wb.CreateCellStyle();
            Assert.AreNotEqual(HorizontalAlignment.Right, clone.Alignment);
            Assert.AreNotEqual(fnt, clone.GetFont(wb));
            Assert.AreNotEqual(18, clone.DataFormat);

            clone.CloneStyleFrom(orig);
            Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment);
            Assert.AreEqual(fnt, clone.GetFont(wb));
            Assert.AreEqual(18, clone.DataFormat);
            Assert.AreEqual(5, wb.NumberOfFonts);

            orig.Alignment = HorizontalAlignment.Left;
            Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment);
        }
Example #4
0
        public void TestWriteSheetFont()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
            IRow r = null;
            //ICell c = null;
            IFont fnt = wb.CreateFont();

            NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();

            fnt.Color      = (NPOI.HSSF.Util.HSSFColor.Red.Index);
            fnt.Boldweight = (short)FontBoldWeight.Bold;
            cs.SetFont(fnt);
            for (short rownum = (short)0; rownum < 100; rownum++)
            {
                r          = s.CreateRow(rownum);
                r.RowStyle = (cs);
                r.CreateCell(0);
            }
            wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);

            SanityChecker sanityChecker = new SanityChecker();

            sanityChecker.CheckHSSFWorkbook(wb);
            Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99");
            Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0");
        }
Example #5
0
        public void TestDataStyle()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet     s  = wb.CreateSheet();
            NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();
            IRow row = s.CreateRow((short)0);

            // with Date:
            cs.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
            row.RowStyle  = (cs);
            row.CreateCell(0);


            // with Calendar:
            row           = s.CreateRow((short)1);
            cs.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
            row.RowStyle  = (cs);
            row.CreateCell(0);

            wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);

            SanityChecker sanityChecker = new SanityChecker();

            sanityChecker.CheckHSSFWorkbook(wb);

            Assert.AreEqual(1, s.LastRowNum, "LAST ROW ");
            Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW ");
        }
Example #6
0
        /// <summary>
        /// Returns a map containing the format properties of the given cell style.
        /// </summary>
        /// <param name="style">cell style</param>
        /// <returns>map of format properties (String -&gt; Object)</returns>
        private static Hashtable GetFormatProperties(NPOI.SS.UserModel.ICellStyle style)
        {
            Hashtable properties = new Hashtable();

            PutShort(properties, ALIGNMENT, (short)style.Alignment);
            PutShort(properties, BORDER_BOTTOM, (short)style.BorderBottom);
            PutShort(properties, BORDER_LEFT, (short)style.BorderLeft);
            PutShort(properties, BORDER_RIGHT, (short)style.BorderRight);
            PutShort(properties, BORDER_TOP, (short)style.BorderTop);
            PutShort(properties, BOTTOM_BORDER_COLOR, style.BottomBorderColor);
            PutShort(properties, DATA_FORMAT, style.DataFormat);
            PutShort(properties, FILL_BACKGROUND_COLOR, style.FillBackgroundColor);
            PutShort(properties, FILL_FOREGROUND_COLOR, style.FillForegroundColor);
            PutShort(properties, FILL_PATTERN, (short)style.FillPattern);
            PutShort(properties, FONT, style.FontIndex);
            PutBoolean(properties, HIDDEN, style.IsHidden);
            PutShort(properties, INDENTION, style.Indention);
            PutShort(properties, LEFT_BORDER_COLOR, style.LeftBorderColor);
            PutBoolean(properties, LOCKED, style.IsLocked);
            PutShort(properties, RIGHT_BORDER_COLOR, style.RightBorderColor);
            PutShort(properties, ROTATION, style.Rotation);
            PutShort(properties, TOP_BORDER_COLOR, style.TopBorderColor);
            PutShort(properties, VERTICAL_ALIGNMENT, (short)style.VerticalAlignment);
            PutBoolean(properties, WRAP_TEXT, style.WrapText);
            return(properties);
        }
Example #7
0
        public void TestDoesNoHarmIfNothingToDo()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            IFont f = wb.CreateFont();

            f.FontName = ("Testing");
            NPOI.SS.UserModel.ICellStyle s = wb.CreateCellStyle();
            s.SetFont(f);

            Assert.AreEqual(5, wb.NumberOfFonts);
            Assert.AreEqual(22, wb.NumCellStyles);

            // Optimise fonts
            HSSFOptimiser.OptimiseFonts(wb);

            Assert.AreEqual(5, wb.NumberOfFonts);
            Assert.AreEqual(22, wb.NumCellStyles);

            Assert.AreEqual(f, s.GetFont(wb));

            // Optimise styles
            HSSFOptimiser.OptimiseCellStyles(wb);

            Assert.AreEqual(5, wb.NumberOfFonts);
            Assert.AreEqual(22, wb.NumCellStyles);

            Assert.AreEqual(f, s.GetFont(wb));
        }
Example #8
0
        /**
         *  This method attempt to find an already existing HSSFCellStyle that matches
         *  what you want the style to be. If it does not find the style, then it
         *  Creates a new one. If it does Create a new one, then it applies the
         *  propertyName and propertyValue to the style. This is necessary because
         *  Excel has an upper limit on the number of Styles that it supports.
         *
         *@param  workbook               The workbook that is being worked with.
         *@param  propertyName           The name of the property that is to be
         *      changed.
         *@param  propertyValue          The value of the property that is to be
         *      changed.
         *@param  cell                   The cell that needs it's style changes
         *@exception  NestableException  Thrown if an error happens.
         */
        public static void SetCellStyleProperty(NPOI.SS.UserModel.ICell cell, HSSFWorkbook workbook, String propertyName, Object propertyValue)
        {
            NPOI.SS.UserModel.ICellStyle originalStyle = cell.CellStyle;
            NPOI.SS.UserModel.ICellStyle newStyle      = null;
            Hashtable values = GetFormatProperties(originalStyle);

            values[propertyName] = propertyValue;

            // index seems like what  index the cellstyle is in the list of styles for a workbook.
            // not good to compare on!
            short numberCellStyles = workbook.NumCellStyles;

            for (short i = 0; i < numberCellStyles; i++)
            {
                NPOI.SS.UserModel.ICellStyle wbStyle = workbook.GetCellStyleAt(i);
                Hashtable wbStyleMap = GetFormatProperties(wbStyle);

                // if (wbStyleMap.Equals(values))
                if (CompareHashTableKeyValueIsEqual(wbStyleMap, values))
                {
                    newStyle = wbStyle;
                    break;
                }
            }

            if (newStyle == null)
            {
                newStyle = workbook.CreateCellStyle();
                SetFormatProperties(newStyle, workbook, values);
            }

            cell.CellStyle = (newStyle);
        }
Example #9
0
        public void TestHashEquals()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet     s   = wb.CreateSheet();
            NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle();
            NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle();
            IRow  row   = s.CreateRow(0);
            ICell cell1 = row.CreateCell(1);
            ICell cell2 = row.CreateCell(2);

            cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
            cs2.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy"));

            cell1.CellStyle = (cs1);
            cell1.SetCellValue(DateTime.Now);

            cell2.CellStyle = (cs2);
            cell2.SetCellValue(DateTime.Now);

            Assert.AreEqual(cs1.GetHashCode(), cs1.GetHashCode());
            Assert.AreEqual(cs2.GetHashCode(), cs2.GetHashCode());
            Assert.IsTrue(cs1.Equals(cs1));
            Assert.IsTrue(cs2.Equals(cs2));

            // Change cs1, hash will alter
            int hash1 = cs1.GetHashCode();

            cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy"));
            Assert.IsFalse(hash1 == cs1.GetHashCode());
        }
Example #10
0
        public void TestDateFormulas()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet s = wb.CreateSheet("TestSheet1");
            IRow  r = null;
            ICell c = null;

            r = s.CreateRow(0);
            c = r.CreateCell(0);

            NPOI.SS.UserModel.ICellStyle cellStyle = wb.CreateCellStyle();
            cellStyle.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy h:mm"));
            c.SetCellValue(new DateTime());
            c.CellStyle = (cellStyle);

            // Assert.AreEqual("Checking hour = " + hour, date.GetTime().GetTime(),
            //              NPOI.SS.UserModel.DateUtil.GetJavaDate(excelDate).GetTime());

            for (int k = 1; k < 100; k++)
            {
                r             = s.CreateRow(k);
                c             = r.CreateCell(0);
                c.CellFormula = ("A" + (k) + "+1");
                c.CellStyle   = cellStyle;
            }

            HSSFTestDataSamples.WriteOutAndReadBack(wb);
        }
Example #11
0
        /// <summary>
        /// 写入DataTable到Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="excelFile"></param>
        public virtual void writeDataTableToExcel(DataTable dt, string excelFile)
        {
            //Excel数据
            MemoryStream memoryStream = new MemoryStream();

            //创建Workbook
            NPOI.XSSF.UserModel.XSSFWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();

            #region 设置Excel样式
            //创建单元格设置对象(普通内容)
            NPOI.SS.UserModel.ICellStyle cellStyleA = workbook.CreateCellStyle();
            cellStyleA.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Left;
            cellStyleA.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            cellStyleA.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleA.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleA.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleA.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleA.WrapText          = true;

            //创建单元格设置对象(普通内容)
            NPOI.SS.UserModel.ICellStyle cellStyleB = workbook.CreateCellStyle();
            cellStyleB.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyleB.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            cellStyleB.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleB.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleB.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleB.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyleB.WrapText          = true;

            //创建设置字体对象(内容字体)
            NPOI.SS.UserModel.IFont fontA = workbook.CreateFont();
            fontA.FontHeightInPoints = 16;//设置字体大小
            fontA.FontName           = "宋体";
            cellStyleA.SetFont(fontA);

            //创建设置字体对象(标题字体)
            NPOI.SS.UserModel.IFont fontB = workbook.CreateFont();
            fontB.FontHeightInPoints = 16;//设置字体大小
            fontB.FontName           = "宋体";
            fontB.Boldweight         = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            cellStyleB.SetFont(fontB);
            #endregion

            //写入基本数据
            writeSheet(workbook, cellStyleA, cellStyleB, dt);

            #region 输出文件
            //输出到流
            workbook.Write(memoryStream);

            //写Excel文件
            File.WriteAllBytes(excelFile, memoryStream.ToArray());
            #endregion
        }
Example #12
0
        public new void TestDefaultColumnStyle()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            NPOI.SS.UserModel.ICellStyle style = wb.CreateCellStyle();
            NPOI.SS.UserModel.ISheet     s     = wb.CreateSheet();
            s.SetDefaultColumnStyle((short)0, style);
            IRow  r = s.CreateRow(0);
            ICell c = r.CreateCell(0);

            Assert.AreEqual(style.Index, c.CellStyle.Index, "style should Match");
        }
Example #13
0
        public void TestWriteSheetStyle()
        {
            string filepath = TempFile.GetTempFilePath("TestWriteSheetStyle",
                                                       ".xls");
            FileStream   out1 = new FileStream(filepath, FileMode.OpenOrCreate);
            HSSFWorkbook wb   = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
            IRow  r   = null;
            ICell c   = null;
            IFont fnt = wb.CreateFont();

            NPOI.SS.UserModel.ICellStyle cs  = wb.CreateCellStyle();
            NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle();

            cs.BorderBottom        = (BorderStyle.Thin);
            cs.BorderLeft          = (BorderStyle.Thin);
            cs.BorderRight         = (BorderStyle.Thin);
            cs.BorderTop           = (BorderStyle.Thin);
            cs.FillForegroundColor = ( short )0xA;
            cs.FillPattern         = FillPattern.SolidForeground;
            fnt.Color               = ( short )0xf;
            fnt.IsItalic            = (true);
            cs2.FillForegroundColor = ( short )0x0;
            cs2.FillPattern         = FillPattern.SolidForeground;
            cs2.SetFont(fnt);
            for (short rownum = ( short )0; rownum < 100; rownum++)
            {
                r = s.CreateRow(rownum);

                // r.SetRowNum(( short ) rownum);
                for (short cellnum = ( short )0; cellnum < 50; cellnum += 2)
                {
                    c = r.CreateCell(cellnum);
                    c.SetCellValue(rownum * 10000 + cellnum
                                   + ((( double )rownum / 1000)
                                      + (( double )cellnum / 10000)));
                    c.CellStyle = (cs);
                    c           = r.CreateCell(cellnum + 1);
                    c.SetCellValue("TEST");
                    c.CellStyle = (cs2);
                }
            }
            wb.Write(out1);
            out1.Close();
            SanityChecker sanityChecker = new SanityChecker();

            sanityChecker.CheckHSSFWorkbook(wb);
            Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99");
            Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0");

            // assert((s.LastRowNum == 99));
        }
 /// <summary>
 /// 获取单元格样式
 /// </summary>
 /// <param name="hssfworkbook">Excel操作类</param>
 /// <returns></returns>
 public static NPOI.SS.UserModel.ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook)
 {
     NPOI.SS.UserModel.ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
     //居中显示
     cellstyle.VerticalAlignment = VerticalAlignment.Center;
     cellstyle.Alignment         = HorizontalAlignment.Center;
     //有边框
     cellstyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
     cellstyle.BorderLeft   = NPOI.SS.UserModel.BorderStyle.Thin;
     cellstyle.BorderRight  = NPOI.SS.UserModel.BorderStyle.Thin;
     cellstyle.BorderTop    = NPOI.SS.UserModel.BorderStyle.Thin;
     return(cellstyle);
 }
Example #15
0
        /// <summary>
        /// 创建EXCEL文档
        /// </summary>
        /// <param name="path">保存路径</param>
        /// <param name="dt">DataTable</param>
        public static void CreatExcel(string fullPath, DataTable dt)
        {
            HSSFWorkbook       hssfworkbook = new HSSFWorkbook();
            SummaryInformation si           = PropertySetFactory.CreateSummaryInformation();

            si.Subject = "主题";
            hssfworkbook.SummaryInformation = si;

            NPOI.SS.UserModel.ISheet hssfSheet = hssfworkbook.CreateSheet("Sheet");
            hssfSheet.DefaultColumnWidth = 18;
            NPOI.SS.UserModel.ICellStyle cellStyle = hssfworkbook.CreateCellStyle();

            cellStyle.Alignment         = HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            //表头
            NPOI.SS.UserModel.IRow tagRow = hssfSheet.CreateRow(0);
            tagRow.RowStyle = cellStyle;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                tagRow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
                tagRow.GetCell(i).CellStyle = cellStyle;
            }
            int rowNum = 1;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow row = hssfSheet.CreateRow(rowNum);
                if (rowNum == 50001)//超过五万条数据,新建一张工作表
                {
                    hssfSheet = hssfworkbook.CreateSheet();
                    rowNum    = 1;
                    NPOI.SS.UserModel.IRow newrow = hssfSheet.CreateRow(0);
                    row = hssfSheet.CreateRow(1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        newrow.CreateCell(j).SetCellValue(dt.Columns[j].ColumnName.ToString());
                    }
                }
                //写入记录
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    row.CreateCell(j).SetCellValue(dt.Rows[i][dt.Columns[j].ColumnName].ToString());
                }
                rowNum++;
            }
            FileStream file = new FileStream(fullPath, FileMode.Create);

            hssfworkbook.Write(file);
            file.Close();
        }
Example #16
0
        public void TestHSSFCellToStringWithDataFormat()
        {
            HSSFWorkbook wb   = new HSSFWorkbook();
            ICell        cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0);

            cell.SetCellValue(new DateTime(2009, 8, 20));
            NPOI.SS.UserModel.ICellStyle cellStyle = wb.CreateCellStyle();
            cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("m/d/yy");
            cell.CellStyle       = cellStyle;
            Assert.AreEqual("8/20/09", cell.ToString());

            NPOI.SS.UserModel.ICellStyle cellStyle2 = wb.CreateCellStyle();
            IDataFormat format = wb.CreateDataFormat();

            cellStyle2.DataFormat = format.GetFormat("YYYY-mm/dd");
            cell.CellStyle        = cellStyle2;
            Assert.AreEqual("2009-08/20", cell.ToString());
        }
Example #17
0
        public void TestWriteSheetFont()
        {
            string filepath = TempFile.GetTempFilePath("TestWriteSheetFont",
                                                       ".xls");
            FileStream   out1 = new FileStream(filepath, FileMode.OpenOrCreate);
            HSSFWorkbook wb   = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
            IRow  r   = null;
            ICell c   = null;
            IFont fnt = wb.CreateFont();

            NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();

            fnt.Color      = (NPOI.HSSF.Util.HSSFColor.Red.Index);
            fnt.Boldweight = (short)FontBoldWeight.Bold;
            cs.SetFont(fnt);
            for (short rownum = ( short )0; rownum < 100; rownum++)
            {
                r = s.CreateRow(rownum);

                // r.SetRowNum(( short ) rownum);
                for (short cellnum = ( short )0; cellnum < 50; cellnum += 2)
                {
                    c = r.CreateCell(cellnum);
                    c.SetCellValue(rownum * 10000 + cellnum
                                   + ((( double )rownum / 1000)
                                      + (( double )cellnum / 10000)));
                    c = r.CreateCell(cellnum + 1);
                    c.SetCellValue("TEST");
                    c.CellStyle = (cs);
                }
            }
            wb.Write(out1);
            out1.Close();
            SanityChecker sanityChecker = new SanityChecker();

            sanityChecker.CheckHSSFWorkbook(wb);
            Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99");
            Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0");

            // assert((s.LastRowNum == 99));
        }
Example #18
0
        public void TestWriteDataFormat()
        {
            string       filepath = TempFile.GetTempFilePath("TestWriteSheetSimple", ".xls");
            FileStream   out1     = new FileStream(filepath, FileMode.OpenOrCreate);
            HSSFWorkbook wb       = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
            IRow        r      = null;
            ICell       c      = null;
            IDataFormat format = wb.CreateDataFormat();

            NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();

            short df = format.GetFormat("0.0");

            cs.DataFormat = (df);

            r           = s.CreateRow(0);
            c           = r.CreateCell(0);
            c.CellStyle = (cs);
            c.SetCellValue(1.25);

            wb.Write(out1);
            out1.Close();

            FileStream      stream   = new FileStream(filepath, FileMode.OpenOrCreate);
            POIFSFileSystem fs       = new POIFSFileSystem(stream);
            HSSFWorkbook    workbook = new HSSFWorkbook(fs);

            NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
            ICell cell =
                sheet.GetRow(0).GetCell(0);

            format = workbook.CreateDataFormat();

            Assert.AreEqual(1.25, cell.NumericCellValue, 1e-10);

            Assert.AreEqual(format.GetFormat(df), "0.0");

            Assert.AreEqual(format, workbook.CreateDataFormat());

            stream.Close();
        }
Example #19
0
        public void TestCloneStyleDiffWB()
        {
            HSSFWorkbook wbOrig = new HSSFWorkbook();

            IFont fnt = wbOrig.CreateFont();

            fnt.FontName = ("TestingFont");
            Assert.AreEqual(5, wbOrig.NumberOfFonts);

            IDataFormat fmt = wbOrig.CreateDataFormat();

            fmt.GetFormat("MadeUpOne");
            fmt.GetFormat("MadeUpTwo");

            NPOI.SS.UserModel.ICellStyle orig = wbOrig.CreateCellStyle();
            orig.Alignment = (HorizontalAlignment.Right);
            orig.SetFont(fnt);
            orig.DataFormat = (fmt.GetFormat("Test##"));

            Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment);
            Assert.AreEqual(fnt, orig.GetFont(wbOrig));
            Assert.AreEqual(fmt.GetFormat("Test##"), orig.DataFormat);

            // Now a style on another workbook
            HSSFWorkbook wbClone = new HSSFWorkbook();

            Assert.AreEqual(4, wbClone.NumberOfFonts);
            IDataFormat fmtClone = wbClone.CreateDataFormat();

            NPOI.SS.UserModel.ICellStyle clone = wbClone.CreateCellStyle();
            Assert.AreEqual(4, wbClone.NumberOfFonts);

            Assert.AreNotEqual(HorizontalAlignment.Right, clone.Alignment);
            Assert.AreNotEqual("TestingFont", clone.GetFont(wbClone).FontName);

            clone.CloneStyleFrom(orig);
            Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment);
            Assert.AreEqual("TestingFont", clone.GetFont(wbClone).FontName);
            Assert.AreEqual(fmtClone.GetFormat("Test##"), clone.DataFormat);
            Assert.AreNotEqual(fmtClone.GetFormat("Test##"), fmt.GetFormat("Test##"));
            Assert.AreEqual(5, wbClone.NumberOfFonts);
        }
Example #20
0
        /// <summary>
        /// 创建excel表头
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="excelSheet"></param>
        protected static void CreateHeader(NPOI.SS.UserModel.ISheet excelSheet, HSSFWorkbook excelWorkbook)
        {
            int cellIndex = 0;

            NPOI.SS.UserModel.IRow row1 = excelSheet.CreateRow(0);

            NPOI.SS.UserModel.ICellStyle cellStyle = excelWorkbook.CreateCellStyle();
            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
            //cellStyle.FillPattern = HSSFCellStyle.SQUARES;
            cellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
            //循环导出列
            foreach (System.Collections.DictionaryEntry de in _listColumnsName)
            {
                NPOI.SS.UserModel.ICell cell = row1.CreateCell(cellIndex);
                cell.CellStyle = cellStyle;
                string cellName = de.Value.ToString().Trim();
                cell.SetCellValue(cellName);
                excelSheet.SetColumnWidth(cellIndex, 15 * 256);
                cellIndex++;
            }
        }
Example #21
0
        public void TestDoesNoHarmIfNothingToDo()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            // New files start with 4 built in fonts, and 21 built in styles
            Assert.AreEqual(4, wb.NumberOfFonts);
            Assert.AreEqual(21, wb.NumCellStyles);

            // Create a test font and style, and use them
            IFont f = wb.CreateFont();

            f.FontName = ("Testing");
            NPOI.SS.UserModel.ICellStyle s = wb.CreateCellStyle();
            s.SetFont(f);

            HSSFSheet sheet = (HSSFSheet)wb.CreateSheet();
            HSSFRow   row   = (HSSFRow)sheet.CreateRow(0);

            row.CreateCell(0).CellStyle = (s);

            // Should have one more than the default of each
            Assert.AreEqual(5, wb.NumberOfFonts);
            Assert.AreEqual(22, wb.NumCellStyles);

            // Optimise fonts
            HSSFOptimiser.OptimiseFonts(wb);

            Assert.AreEqual(5, wb.NumberOfFonts);
            Assert.AreEqual(22, wb.NumCellStyles);

            Assert.AreEqual(f, s.GetFont(wb));

            // Optimise styles
            HSSFOptimiser.OptimiseCellStyles(wb);

            Assert.AreEqual(5, wb.NumberOfFonts);
            Assert.AreEqual(22, wb.NumCellStyles);

            Assert.AreEqual(f, s.GetFont(wb));
        }
Example #22
0
 /// <summary>
 /// Sets the format properties of the given style based on the given map.
 /// </summary>
 /// <param name="style">The cell style</param>
 /// <param name="workbook">The parent workbook.</param>
 /// <param name="properties">The map of format properties (String -&gt; Object).</param>
 private static void SetFormatProperties(
     NPOI.SS.UserModel.ICellStyle style, HSSFWorkbook workbook, Hashtable properties)
 {
     style.Alignment           = (NPOI.SS.UserModel.HorizontalAlignment)GetShort(properties, ALIGNMENT);
     style.BorderBottom        = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_BOTTOM);
     style.BorderLeft          = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_LEFT);
     style.BorderRight         = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_RIGHT);
     style.BorderTop           = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_TOP);
     style.BottomBorderColor   = (GetShort(properties, BOTTOM_BORDER_COLOR));
     style.DataFormat          = (GetShort(properties, DATA_FORMAT));
     style.FillBackgroundColor = (GetShort(properties, FILL_BACKGROUND_COLOR));
     style.FillForegroundColor = (GetShort(properties, FILL_FOREGROUND_COLOR));
     style.FillPattern         = (NPOI.SS.UserModel.FillPattern)GetShort(properties, FILL_PATTERN);
     style.SetFont(workbook.GetFontAt(GetShort(properties, FONT)));
     style.IsHidden          = (GetBoolean(properties, HIDDEN));
     style.Indention         = (GetShort(properties, INDENTION));
     style.LeftBorderColor   = (GetShort(properties, LEFT_BORDER_COLOR));
     style.IsLocked          = (GetBoolean(properties, LOCKED));
     style.RightBorderColor  = (GetShort(properties, RIGHT_BORDER_COLOR));
     style.Rotation          = (GetShort(properties, ROTATION));
     style.TopBorderColor    = (GetShort(properties, TOP_BORDER_COLOR));
     style.VerticalAlignment = (NPOI.SS.UserModel.VerticalAlignment)GetShort(properties, VERTICAL_ALIGNMENT);
     style.WrapText          = (GetBoolean(properties, WRAP_TEXT));
 }
Example #23
0
        /// <summary>
        /// NPOI 宴会统计导出
        /// </summary>
        /// <param name="id"></param>
        /// <param name="ids"></param>
        public void Export(string id, string ids)
        {
            Response.Clear();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";


            NPOI.XSSF.UserModel.XSSFWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
            NPOI.SS.UserModel.ISheet         sheet1   = workbook.CreateSheet("宴会统计");

            //excel格式化
            NPOI.SS.UserModel.ICellStyle dateStyle = workbook.CreateCellStyle();
            dateStyle.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy/m/d h:mm:ss");

            NPOI.SS.UserModel.ICellStyle numberStyle = workbook.CreateCellStyle();
            numberStyle.DataFormat = workbook.CreateDataFormat().GetFormat("0.00000");

            NPOI.SS.UserModel.ICellStyle textStyle = workbook.CreateCellStyle();
            textStyle.DataFormat = workbook.CreateDataFormat().GetFormat("@");

            //设置单元格宽度
            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();



            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("姓名");
            row1.CreateCell(1).SetCellValue("电话号码");
            row1.CreateCell(2).SetCellValue("签到号");
            row1.CreateCell(3).SetCellValue("红包");
            row1.CreateCell(4).SetCellValue("礼物");
            row1.CreateCell(5).SetCellValue("实际人数");
            row1.CreateCell(6).SetCellValue("预计人数");


            //设置列宽
            row1.Sheet.SetColumnWidth(0, 80 * 50);
            row1.Sheet.SetColumnWidth(1, 80 * 50);
            row1.Sheet.SetColumnWidth(2, 50 * 50);
            row1.Sheet.SetColumnWidth(3, 80 * 50);
            row1.Sheet.SetColumnWidth(4, 150 * 50);
            row1.Sheet.SetColumnWidth(5, 80 * 50);
            row1.Sheet.SetColumnWidth(6, 80 * 50);


            MessasgeData mgdata = new MessasgeData();

            SqlParameter[] pms =
            {
                new  SqlParameter("@meeting", id),
                new SqlParameter("@ms",       ids)
            };
            mgdata = Datafun.MgfunctionData("select MeetingName from tb_Meeting where id=@meeting", pms);
            if (mgdata.Mgdatacount > 0)
            {
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "" + mgdata.Mgdata.Rows[0][0].ToString() + ".xlsx"));//添加Excel名字
            }
            else
            {
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "宴会统计.xlsx"));//添加Excel名字
            }
            mgdata = Datafun.MgfunctionData("Tj_rstj_poc", pms, "poc");
            for (int i = 0; i < mgdata.Mgdata.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);


                rowtemp.CreateCell(0).SetCellValue(mgdata.Mgdata.Rows[i][0].ToString());
                rowtemp.CreateCell(1).SetCellValue(mgdata.Mgdata.Rows[i][1].ToString());
                rowtemp.CreateCell(2).SetCellValue(mgdata.Mgdata.Rows[i][2].ToString());
                rowtemp.CreateCell(3).SetCellValue(mgdata.Mgdata.Rows[i][3].ToString());
                rowtemp.CreateCell(4).SetCellValue(mgdata.Mgdata.Rows[i][4].ToString());
                rowtemp.CreateCell(5).SetCellValue(mgdata.Mgdata.Rows[i][5].ToString());
                rowtemp.CreateCell(6).SetCellValue(mgdata.Mgdata.Rows[i][6].ToString());



                rowtemp.GetCell(0).CellStyle = textStyle;
                rowtemp.GetCell(1).CellStyle = textStyle;
                rowtemp.GetCell(2).CellStyle = textStyle;
                rowtemp.GetCell(3).CellStyle = numberStyle;
                rowtemp.GetCell(4).CellStyle = textStyle;
                rowtemp.GetCell(5).CellStyle = textStyle;
                rowtemp.GetCell(6).CellStyle = numberStyle;
            }
            //写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            workbook.Write(ms);
            Response.BinaryWrite(ms.ToArray());

            Response.Flush();
            Response.End();
        }
Example #24
0
        /// <summary>
        /// NPOI 导出会议的管理人员
        /// </summary>
        /// <param name="id"></param>
        /// <param name="ids"></param>
        public void ExportMeeting()
        {
            Response.Clear();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";


            NPOI.XSSF.UserModel.XSSFWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
            NPOI.SS.UserModel.ISheet         sheet1   = workbook.CreateSheet("宴会统计");

            //excel格式化
            NPOI.SS.UserModel.ICellStyle dateStyle = workbook.CreateCellStyle();
            dateStyle.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy/m/d h:mm:ss");

            NPOI.SS.UserModel.ICellStyle numberStyle = workbook.CreateCellStyle();
            numberStyle.DataFormat = workbook.CreateDataFormat().GetFormat("0.00000");

            NPOI.SS.UserModel.ICellStyle textStyle = workbook.CreateCellStyle();
            textStyle.DataFormat = workbook.CreateDataFormat().GetFormat("@");

            //设置单元格宽度
            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();



            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("姓名");
            row1.CreateCell(1).SetCellValue("电话号码");
            row1.CreateCell(2).SetCellValue("会议名称");
            row1.CreateCell(3).SetCellValue("开始时间");
            row1.CreateCell(4).SetCellValue("结束时间");



            //设置列宽
            row1.Sheet.SetColumnWidth(0, 100 * 50);
            row1.Sheet.SetColumnWidth(1, 100 * 50);
            row1.Sheet.SetColumnWidth(2, 150 * 50);
            row1.Sheet.SetColumnWidth(3, 100 * 50);
            row1.Sheet.SetColumnWidth(4, 100 * 50);



            MessasgeData mgdata = new MessasgeData();

            mgdata = Datafun.MgfunctionData("select Bank,UserName,b.MeetingName,convert(nvarchar(11),Start_Date,120) ,convert(nvarchar(11),End_Date,120) from tb_login a left join tb_Meeting b on a.Meeting=b.id where Lvl=1 and a.isdel=1 ");
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "会议管理人员.xlsx"));    //添加Excel名字

            for (int i = 0; i < mgdata.Mgdata.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);


                rowtemp.CreateCell(0).SetCellValue(mgdata.Mgdata.Rows[i][0].ToString());
                rowtemp.CreateCell(1).SetCellValue(mgdata.Mgdata.Rows[i][1].ToString());
                rowtemp.CreateCell(2).SetCellValue(mgdata.Mgdata.Rows[i][2].ToString());
                rowtemp.CreateCell(3).SetCellValue(mgdata.Mgdata.Rows[i][3].ToString());
                rowtemp.CreateCell(4).SetCellValue(mgdata.Mgdata.Rows[i][4].ToString());



                rowtemp.GetCell(0).CellStyle = textStyle;
                rowtemp.GetCell(1).CellStyle = textStyle;
                rowtemp.GetCell(2).CellStyle = textStyle;
                rowtemp.GetCell(3).CellStyle = numberStyle;
                rowtemp.GetCell(4).CellStyle = textStyle;
            }
            //写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            workbook.Write(ms);
            Response.BinaryWrite(ms.ToArray());

            Response.Flush();
            Response.End();
        }
Example #25
0
        /// <summary>
        /// 导出数据行
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="drSource"></param>
        /// <param name="currentExcelRow"></param>
        /// <param name="excelSheet"></param>
        /// <param name="excelWorkBook"></param>
        protected static void InsertCell(DataTable dtSource, DataRow drSource, NPOI.SS.UserModel.IRow currentExcelRow, NPOI.SS.UserModel.ISheet excelSheet, HSSFWorkbook excelWorkBook, NPOI.SS.UserModel.ICellStyle cellStyle_DateTime)
        {
            for (int cellIndex = 0; cellIndex < _listColumnsName.Count; cellIndex++)
            {
                //列名称
                string columnsName = _listColumnsName.GetKey(cellIndex).ToString();
                NPOI.SS.UserModel.ICell newCell = null;
                System.Type             rowType = drSource[columnsName].GetType();
                string drValue = drSource[columnsName].ToString().Trim();
                switch (rowType.ToString())
                {
                case "System.String":    //字符串类型
                    drValue = drValue.Replace("&", "&");
                    drValue = drValue.Replace(">", ">");
                    drValue = drValue.Replace("<", "<");
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(drValue);
                    break;

                case "System.DateTime":    //日期类型
                    DateTime dateV;
                    DateTime.TryParse(drValue, out dateV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(dateV);

                    //格式化显示
                    newCell.CellStyle = cellStyle_DateTime;

                    break;

                case "System.Boolean":    //布尔型
                    bool boolV = false;
                    bool.TryParse(drValue, out boolV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(boolV);
                    break;

                case "System.Int16":    //整型
                case "System.Int32":
                case "System.Int64":
                case "System.Byte":
                    int intV = 0;
                    int.TryParse(drValue, out intV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(intV.ToString());
                    break;

                case "System.Decimal":    //浮点型
                case "System.Double":
                    double doubV = 0;
                    double.TryParse(drValue, out doubV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(doubV);
                    break;

                case "System.DBNull":    //空值处理
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue("");
                    break;

                case "System.Guid":    //空值处理
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(drValue);
                    break;

                default:
                    throw (new Exception(rowType.ToString() + ":类型数据无法处理!"));
                }
            }
        }
Example #26
0
        /// <summary>
        /// Goes through the Wokrbook, optimising the cell styles
        /// by removing duplicate ones.
        /// For best results, optimise the fonts via a call to
        /// OptimiseFonts(HSSFWorkbook) first
        /// </summary>
        /// <param name="workbook">The workbook in which to optimise the cell styles</param>
        public static void OptimiseCellStyles(HSSFWorkbook workbook)
        {
            // Where each style has ended up, and if we need to
            //  delete the record for it. Start off with no change
            short[] newPos =
                new short[workbook.Workbook.NumExFormats];
            bool[] zapRecords = new bool[newPos.Length];
            for (int i = 0; i < newPos.Length; i++)
            {
                newPos[i]     = (short)i;
                zapRecords[i] = false;
            }

            // Get each style record, so we can do deletes
            //  without Getting confused
            ExtendedFormatRecord[] xfrs = new ExtendedFormatRecord[newPos.Length];
            for (int i = 0; i < newPos.Length; i++)
            {
                xfrs[i] = workbook.Workbook.GetExFormatAt(i);
            }

            // Loop over each style, seeing if it is the same
            //  as an earlier one. If it is, point users of the
            //  later duplicate copy to the earlier one, and
            //  mark the later one as needing deleting
            // Only work on user added ones, which come after 20
            for (int i = 21; i < newPos.Length; i++)
            {
                // Check this one for being a duplicate
                //  of an earlier one
                int earlierDuplicate = -1;
                for (int j = 0; j < i && earlierDuplicate == -1; j++)
                {
                    ExtendedFormatRecord xfCheck = workbook.Workbook.GetExFormatAt(j);
                    if (xfCheck.Equals(xfrs[i]))
                    {
                        earlierDuplicate = j;
                    }
                }

                // If we got a duplicate, mark it as such
                if (earlierDuplicate != -1)
                {
                    newPos[i]     = (short)earlierDuplicate;
                    zapRecords[i] = true;
                }
            }

            // Update the new positions based on
            //  deletes that have occurred between
            //  the start and them
            // Only work on user added ones, which come after 20
            for (int i = 21; i < newPos.Length; i++)
            {
                // Find the number deleted to that
                //  point, and adjust
                short preDeletePos = newPos[i];
                short newPosition  = preDeletePos;
                for (int j = 0; j < preDeletePos; j++)
                {
                    if (zapRecords[j])
                    {
                        newPosition--;
                    }
                }

                // Update the new position
                newPos[i] = newPosition;
            }

            // Zap the un-needed user style records
            for (int i = 21; i < newPos.Length; i++)
            {
                if (zapRecords[i])
                {
                    workbook.Workbook.RemoveExFormatRecord(
                        xfrs[i]
                        );
                }
            }

            // Finally, update the cells to point at
            //  their new extended format records
            for (int sheetNum = 0; sheetNum < workbook.NumberOfSheets; sheetNum++)
            {
                HSSFSheet   s   = (HSSFSheet)workbook.GetSheetAt(sheetNum);
                IEnumerator rIt = s.GetRowEnumerator();
                while (rIt.MoveNext())
                {
                    HSSFRow     row = (HSSFRow)rIt.Current;
                    IEnumerator cIt = row.GetEnumerator();
                    while (cIt.MoveNext())
                    {
                        ICell cell  = (HSSFCell)cIt.Current;
                        short oldXf = ((HSSFCell)cell).CellValueRecord.XFIndex;
                        NPOI.SS.UserModel.ICellStyle newStyle = workbook.GetCellStyleAt(
                            newPos[oldXf]
                            );
                        cell.CellStyle = (newStyle);
                    }
                }
            }
        }
Example #27
0
        /// <summary>
        /// DataTable导出到Excel的MemoryStream xlsx
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <param name="strFileName">文件名</param>
        public static MemoryStream ExportXlsx(IEnumerable <DataTable> dataTables, string strHeaderText, string passaord = null)
        {
            XSSFWorkbook workbook = new XSSFWorkbook();
            int          i        = 0;

            NPOI.SS.UserModel.ICellStyle  dateStyle = workbook.CreateCellStyle();
            NPOI.SS.UserModel.IDataFormat format    = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            #region 右击文件 属性信息
            {
                //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                //    dsi.Company = "NPOI";

                //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                //    si.Author = "文件作者信息"; //填加xlsx文件作者信息
                //    si.ApplicationName = "创建程序信息"; //填加xlsx文件创建程序信息
                //    si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
                //    si.Comments = "作者信息"; //填加xls文件作者信息
                //    si.Title = "标题信息"; //填加xls文件标题信息
                //    si.Subject = "主题信息";//填加文件主题信息
                //    si.CreateDateTime = DateTime.Now;
                //    workbook.GetProperties().CustomProperties.AddProperty("Company", "NPOI");
                //    if (!workbook.GetProperties().CustomProperties.Contains("Company"))
                //        workbook.GetProperties().CustomProperties.AddProperty("Company", dsi.Company);
            }
            #endregion

            foreach (DataTable dt in dataTables)
            {
                string sheetName = string.IsNullOrEmpty(dt.TableName)
                    ? "Sheet " + (++i).ToString()
                    : dt.TableName;
                ISheet sheet = workbook.CreateSheet(sheetName);
                if (string.IsNullOrEmpty(passaord) == false)
                {
                    sheet.ProtectSheet(passaord);
                }

                int rowIndex = 0;
                #region 表头及样式
                {
                    if (string.IsNullOrEmpty(strHeaderText) == false)
                    {
                        NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(rowIndex);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(strHeaderText);

                        NPOI.SS.UserModel.ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                        NPOI.SS.UserModel.IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight         = 700;
                        headStyle.SetFont(font);
                        headerRow.GetCell(0).CellStyle = headStyle;
                        sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));
                        rowIndex += 1;
                    }
                    //headerRow.Dispose();
                }
                #endregion


                #region 列头及样式
                {
                    //取得列宽
                    int[] arrColWidth = new int[dt.Columns.Count];
                    foreach (DataColumn item in dt.Columns)
                    {
                        arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
                    }
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            int intTemp = Encoding.GetEncoding(936).GetBytes(dt.Rows[k][j].ToString()).Length;
                            if (intTemp > arrColWidth[j])
                            {
                                arrColWidth[j] = intTemp;
                            }
                        }
                    }

                    NPOI.SS.UserModel.IRow       headerRow = sheet.CreateRow(rowIndex);
                    NPOI.SS.UserModel.ICellStyle headStyle = workbook.CreateCellStyle();
                    headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    NPOI.SS.UserModel.IFont font = workbook.CreateFont();
                    font.FontHeightInPoints = 10;
                    font.Boldweight         = 700;
                    headStyle.SetFont(font);
                    foreach (DataColumn column in dt.Columns)
                    {
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                        headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                        //设置列宽
                        sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                    }
                    //headerRow.Dispose();
                    rowIndex += 1;
                }
                #endregion

                //#region 表头
                //for (int j = 0; j < dt.Columns.Count; j++)
                //{
                //    string columnName = string.IsNullOrEmpty(dt.Columns[j].ColumnName)
                //        ? "Column " + j.ToString()
                //        : dt.Columns[j].ColumnName;
                //    headerRow.CreateCell(j).SetCellValue(columnName);
                //}
                //#endregion
                #region 内容
                for (int a = 0; a < dt.Rows.Count; a++)
                {
                    DataRow dr  = dt.Rows[a];
                    IRow    row = sheet.CreateRow(a + rowIndex);
                    for (int b = 0; b < dt.Columns.Count; b++)
                    {
                        row.CreateCell(b).SetCellValue(dr[b] != DBNull.Value ? dr[b].ToString() : string.Empty);
                        DataColumn dc = dt.Columns[b];
                        NPOI.SS.UserModel.ICell newCell = row.CreateCell(dc.Ordinal);

                        string drValue = dr[b].ToString();

                        switch (dc.DataType.ToString())
                        {
                        case "System.String":    //字符串类型
                            newCell.SetCellValue(drValue);
                            break;

                        case "System.DateTime":    //日期类型
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);
                            newCell.CellStyle = dateStyle;    //格式化显示
                            break;

                        case "System.Boolean":    //布尔型
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;

                        case "System.Int16":    //整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;

                        case "System.Decimal":    //浮点型
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;

                        case "System.DBNull":    //空值处理
                            newCell.SetCellValue("");
                            break;

                        default:
                            newCell.SetCellValue("");
                            break;
                        }
                    }
                }
                #endregion
            }

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                // ms.Position = 0;

                // sheet.Dispose();
                //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
                return(ms);
            }
        }
Example #28
0
        /// <summary>
        /// DataTable导出到Excel的MemoryStream
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        public static MemoryStream Export(DataTable dtSource, string strHeaderText, string passaord = null)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();
            if (string.IsNullOrEmpty(passaord) == false)
            {
                sheet.ProtectSheet(passaord);
            }

            #region 右击文件 属性信息
            {
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "NPOI";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author                   = "文件作者信息";  //填加xls文件作者信息
                si.ApplicationName          = "创建程序信息";  //填加xls文件创建程序信息
                si.LastAuthor               = "最后保存者信息"; //填加xls文件最后保存者信息
                si.Comments                 = "作者信息";    //填加xls文件作者信息
                si.Title                    = "标题信息";    //填加xls文件标题信息
                si.Subject                  = "主题信息";    //填加文件主题信息
                si.CreateDateTime           = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion

            NPOI.SS.UserModel.ICellStyle  dateStyle = workbook.CreateCellStyle();
            NPOI.SS.UserModel.IDataFormat format    = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //取得列宽
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = 0;
            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表,填充表头,填充列头,样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                        if (string.IsNullOrEmpty(passaord) == false)
                        {
                            sheet.ProtectSheet(passaord);
                        }
                    }

                    #region 表头及样式
                    {
                        if (string.IsNullOrEmpty(strHeaderText) == false)
                        {
                            NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
                            headerRow.HeightInPoints = 25;
                            headerRow.CreateCell(0).SetCellValue(strHeaderText);

                            NPOI.SS.UserModel.ICellStyle headStyle = workbook.CreateCellStyle();
                            headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                            NPOI.SS.UserModel.IFont font = workbook.CreateFont();
                            font.FontHeightInPoints = 20;
                            font.Boldweight         = 700;
                            headStyle.SetFont(font);
                            headerRow.GetCell(0).CellStyle = headStyle;
                            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                            rowIndex += 1;
                        }
                        //headerRow.Dispose();
                    }
                    #endregion


                    #region 列头及样式
                    {
                        NPOI.SS.UserModel.IRow       headerRow = sheet.CreateRow(rowIndex);
                        NPOI.SS.UserModel.ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                        NPOI.SS.UserModel.IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight         = 700;
                        headStyle.SetFont(font);
                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                            //设置列宽
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                        }
                        //headerRow.Dispose();
                        rowIndex += 1;
                    }
                    #endregion
                }
                #endregion


                #region 填充内容
                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    NPOI.SS.UserModel.ICell newCell = dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                    case "System.String":    //字符串类型
                        newCell.SetCellValue(drValue);
                        break;

                    case "System.DateTime":    //日期类型
                        DateTime dateV;
                        DateTime.TryParse(drValue, out dateV);
                        newCell.SetCellValue(dateV);

                        newCell.CellStyle = dateStyle;    //格式化显示
                        break;

                    case "System.Boolean":    //布尔型
                        bool boolV = false;
                        bool.TryParse(drValue, out boolV);
                        newCell.SetCellValue(boolV);
                        break;

                    case "System.Int16":    //整型
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV = 0;
                        int.TryParse(drValue, out intV);
                        newCell.SetCellValue(intV);
                        break;

                    case "System.Decimal":    //浮点型
                    case "System.Double":
                        double doubV = 0;
                        double.TryParse(drValue, out doubV);
                        newCell.SetCellValue(doubV);
                        break;

                    case "System.DBNull":    //空值处理
                        newCell.SetCellValue("");
                        break;

                    default:
                        newCell.SetCellValue("");
                        break;
                    }
                }
                #endregion

                rowIndex++;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                // sheet.Dispose();
                //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
                return(ms);
            }
        }
Example #29
0
        public void TestOptimiseStyles()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            // Two fonts
            Assert.AreEqual(4, wb.NumberOfFonts);

            IFont f1 = wb.CreateFont();

            f1.FontHeight = ((short)11);
            f1.FontName   = ("Testing");

            IFont f2 = wb.CreateFont();

            f2.FontHeight = ((short)22);
            f2.FontName   = ("Also Testing");

            Assert.AreEqual(6, wb.NumberOfFonts);


            // Several styles
            Assert.AreEqual(21, wb.NumCellStyles);

            NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle();
            cs1.SetFont(f1);

            NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle();
            cs2.SetFont(f2);

            NPOI.SS.UserModel.ICellStyle cs3 = wb.CreateCellStyle();
            cs3.SetFont(f1);

            NPOI.SS.UserModel.ICellStyle cs4 = wb.CreateCellStyle();
            cs4.SetFont(f1);
            cs4.Alignment = HorizontalAlignment.CenterSelection;// ((short)22);

            NPOI.SS.UserModel.ICellStyle cs5 = wb.CreateCellStyle();
            cs5.SetFont(f2);
            cs5.Alignment = HorizontalAlignment.Fill; //((short)111);

            NPOI.SS.UserModel.ICellStyle cs6 = wb.CreateCellStyle();
            cs6.SetFont(f2);

            Assert.AreEqual(27, wb.NumCellStyles);


            // Use them
            NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
            IRow r = s.CreateRow(0);

            r.CreateCell(0).CellStyle = (cs1);
            r.CreateCell(1).CellStyle = (cs2);
            r.CreateCell(2).CellStyle = (cs3);
            r.CreateCell(3).CellStyle = (cs4);
            r.CreateCell(4).CellStyle = (cs5);
            r.CreateCell(5).CellStyle = (cs6);
            r.CreateCell(6).CellStyle = (cs1);
            r.CreateCell(7).CellStyle = (cs2);

            Assert.AreEqual(21, ((HSSFCell)r.GetCell(0)).CellValueRecord.XFIndex);
            Assert.AreEqual(26, ((HSSFCell)r.GetCell(5)).CellValueRecord.XFIndex);
            Assert.AreEqual(21, ((HSSFCell)r.GetCell(6)).CellValueRecord.XFIndex);


            // Optimise
            HSSFOptimiser.OptimiseCellStyles(wb);


            // Check
            Assert.AreEqual(6, wb.NumberOfFonts);
            Assert.AreEqual(25, wb.NumCellStyles);

            // cs1 -> 21
            Assert.AreEqual(21, ((HSSFCell)r.GetCell(0)).CellValueRecord.XFIndex);
            // cs2 -> 22
            Assert.AreEqual(22, ((HSSFCell)r.GetCell(1)).CellValueRecord.XFIndex);
            Assert.AreEqual(22, r.GetCell(1).CellStyle.GetFont(wb).FontHeight);
            // cs3 = cs1 -> 21
            Assert.AreEqual(21, ((HSSFCell)r.GetCell(2)).CellValueRecord.XFIndex);
            // cs4 --> 24 -> 23
            Assert.AreEqual(23, ((HSSFCell)r.GetCell(3)).CellValueRecord.XFIndex);
            // cs5 --> 25 -> 24
            Assert.AreEqual(24, ((HSSFCell)r.GetCell(4)).CellValueRecord.XFIndex);
            // cs6 = cs2 -> 22
            Assert.AreEqual(22, ((HSSFCell)r.GetCell(5)).CellValueRecord.XFIndex);
            // cs1 -> 21
            Assert.AreEqual(21, ((HSSFCell)r.GetCell(6)).CellValueRecord.XFIndex);
            // cs2 -> 22
            Assert.AreEqual(22, ((HSSFCell)r.GetCell(7)).CellValueRecord.XFIndex);


            // Add a new duplicate, and two that aren't used
            HSSFCellStyle csD = (HSSFCellStyle)wb.CreateCellStyle();

            csD.SetFont(f1);
            r.CreateCell(8).CellStyle = (csD);

            HSSFFont f3 = (HSSFFont)wb.CreateFont();

            f3.FontHeight = ((short)23);
            f3.FontName   = ("Testing 3");
            HSSFFont f4 = (HSSFFont)wb.CreateFont();

            f4.FontHeight = ((short)24);
            f4.FontName   = ("Testing 4");

            HSSFCellStyle csU1 = (HSSFCellStyle)wb.CreateCellStyle();

            csU1.SetFont(f3);
            HSSFCellStyle csU2 = (HSSFCellStyle)wb.CreateCellStyle();

            csU2.SetFont(f4);

            // Check before the optimise
            Assert.AreEqual(8, wb.NumberOfFonts);
            Assert.AreEqual(28, wb.NumCellStyles);

            // Optimise, should remove the two un-used ones and the one duplicate
            HSSFOptimiser.OptimiseCellStyles(wb);

            // Check
            Assert.AreEqual(8, wb.NumberOfFonts);
            Assert.AreEqual(25, wb.NumCellStyles);

            // csD -> cs1 -> 21
            Assert.AreEqual(21, ((HSSFCell)r.GetCell(8)).CellValueRecord.XFIndex);
        }
Example #30
0
        public void TestOptimiseFonts()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            // Add 6 fonts, some duplicates
            IFont f1 = wb.CreateFont();

            f1.FontHeight = ((short)11);
            f1.FontName   = ("Testing");

            IFont f2 = wb.CreateFont();

            f2.FontHeight = ((short)22);
            f2.FontName   = ("Also Testing");

            IFont f3 = wb.CreateFont();

            f3.FontHeight = ((short)33);
            f3.FontName   = ("Unique");

            IFont f4 = wb.CreateFont();

            f4.FontHeight = ((short)11);
            f4.FontName   = ("Testing");

            IFont f5 = wb.CreateFont();

            f5.FontHeight = ((short)22);
            f5.FontName   = ("Also Testing");

            IFont f6 = wb.CreateFont();

            f6.FontHeight = ((short)66);
            f6.FontName   = ("Also Unique");



            // Use all three of the four in cell styles
            Assert.AreEqual(21, wb.NumCellStyles);

            NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle();
            cs1.SetFont(f1);
            Assert.AreEqual(5, cs1.FontIndex);

            NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle();
            cs2.SetFont(f4);
            Assert.AreEqual(8, cs2.FontIndex);

            NPOI.SS.UserModel.ICellStyle cs3 = wb.CreateCellStyle();
            cs3.SetFont(f5);
            Assert.AreEqual(9, cs3.FontIndex);

            NPOI.SS.UserModel.ICellStyle cs4 = wb.CreateCellStyle();
            cs4.SetFont(f6);
            Assert.AreEqual(10, cs4.FontIndex);

            Assert.AreEqual(25, wb.NumCellStyles);


            // And three in rich text
            NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
            IRow r = s.CreateRow(0);

            HSSFRichTextString rtr1 = new HSSFRichTextString("Test");

            rtr1.ApplyFont(0, 2, f1);
            rtr1.ApplyFont(3, 4, f2);
            r.CreateCell(0).SetCellValue(rtr1);

            HSSFRichTextString rtr2 = new HSSFRichTextString("AlsoTest");

            rtr2.ApplyFont(0, 2, f3);
            rtr2.ApplyFont(3, 5, f5);
            rtr2.ApplyFont(6, 8, f6);
            r.CreateCell(1).SetCellValue(rtr2);


            // Check what we have now
            Assert.AreEqual(10, wb.NumberOfFonts);
            Assert.AreEqual(25, wb.NumCellStyles);

            // Optimise
            HSSFOptimiser.OptimiseFonts(wb);

            // Check font count
            Assert.AreEqual(8, wb.NumberOfFonts);
            Assert.AreEqual(25, wb.NumCellStyles);

            // Check font use in cell styles
            Assert.AreEqual(5, cs1.FontIndex);
            Assert.AreEqual(5, cs2.FontIndex); // duplicate of 1
            Assert.AreEqual(6, cs3.FontIndex); // duplicate of 2
            Assert.AreEqual(8, cs4.FontIndex); // two have gone


            // And in rich text

            // RTR 1 had f1 and f2, unchanged
            Assert.AreEqual(5, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(0));
            Assert.AreEqual(5, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(1));
            Assert.AreEqual(6, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(3));
            Assert.AreEqual(6, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(4));

            // RTR 2 had f3 (unchanged), f5 (=f2) and f6 (moved down)
            Assert.AreEqual(7, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(0));
            Assert.AreEqual(7, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(1));
            Assert.AreEqual(6, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(3));
            Assert.AreEqual(6, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(4));
            Assert.AreEqual(8, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(6));
            Assert.AreEqual(8, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(7));
        }