Пример #1
0
        public ISheet CreateSheet(string sheetname)
        {
            if (sheetname == null)
            {
                throw new ArgumentException("sheetName must not be null");
            }
            if (this.ContainsSheet(sheetname, this.sheets.Count))
            {
                throw new ArgumentException("The workbook already contains a sheet of this name");
            }
            if (sheetname.Length > 31)
            {
                sheetname = sheetname.Substring(0, 31);
            }
            WorkbookUtil.ValidateSheetName(sheetname);
            CT_Sheet ctSheet = this.AddSheet(sheetname);
            int      idx     = 1;

            foreach (XSSFSheet sheet in this.sheets)
            {
                idx = (int)Math.Max((long)(sheet.sheet.sheetId + 1U), (long)idx);
            }
            XSSFSheet relationship = (XSSFSheet)this.CreateRelationship((POIXMLRelation)XSSFRelation.WORKSHEET, (POIXMLFactory)XSSFFactory.GetInstance(), idx);

            relationship.sheet = ctSheet;
            ctSheet.id         = relationship.GetPackageRelationship().Id;
            ctSheet.sheetId    = (uint)idx;
            if (this.sheets.Count == 0)
            {
                relationship.IsSelected = true;
            }
            this.sheets.Add(relationship);
            return((ISheet)relationship);
        }
Пример #2
0
        static void Main(string[] args)
        {
            IWorkbook wb     = new XSSFWorkbook();
            ISheet    sheet1 = wb.CreateSheet("First Sheet");
            ISheet    sheet2 = wb.CreateSheet("Second Sheet");


            // Note that sheet name is Excel must not exceed 31 characters
            // and must not contain any of the any of the following characters:
            // 0x0000
            // 0x0003
            // colon (:)
            // backslash (\)
            // asterisk (*)
            // question mark (?)
            // forward slash (/)
            // opening square bracket ([)
            // closing square bracket (])

            // You can use org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}
            // for a safe way to create valid names, this utility replaces invalid characters with a space (' ')
            String safeName = WorkbookUtil.CreateSafeSheetName("[O'Brien's sales*?]");
            ISheet sheet3   = wb.CreateSheet(safeName);

            FileStream sw = File.Create("newWorksheet.xls");

            wb.Write(sw);
            sw.Close();
        }
Пример #3
0
        public void TestCreateSafeNames()
        {
            String p      = "Sheet1";
            String actual = WorkbookUtil.CreateSafeSheetName(p);

            Assert.AreEqual(p, actual);

            p      = "O'Brien's sales";
            actual = WorkbookUtil.CreateSafeSheetName(p);
            Assert.AreEqual(p, actual);

            p      = " data # ";
            actual = WorkbookUtil.CreateSafeSheetName(p);
            Assert.AreEqual(p, actual);

            p      = "data $1.00";
            actual = WorkbookUtil.CreateSafeSheetName(p);
            Assert.AreEqual(p, actual);

            // now the replaced versions ...
            actual = WorkbookUtil.CreateSafeSheetName("data?");
            Assert.AreEqual("data ", actual);

            actual = WorkbookUtil.CreateSafeSheetName("abc/def");
            Assert.AreEqual("abc def", actual);

            actual = WorkbookUtil.CreateSafeSheetName("data[0]");
            Assert.AreEqual("data 0 ", actual);

            actual = WorkbookUtil.CreateSafeSheetName("data*");
            Assert.AreEqual("data ", actual);

            actual = WorkbookUtil.CreateSafeSheetName("abc\\def");
            Assert.AreEqual("abc def", actual);

            actual = WorkbookUtil.CreateSafeSheetName("'data");
            Assert.AreEqual(" data", actual);

            actual = WorkbookUtil.CreateSafeSheetName("data'");
            Assert.AreEqual("data ", actual);

            actual = WorkbookUtil.CreateSafeSheetName("d'at'a");
            Assert.AreEqual("d'at'a", actual);

            actual = WorkbookUtil.CreateSafeSheetName(null);
            Assert.AreEqual("null", actual);

            actual = WorkbookUtil.CreateSafeSheetName("");
            Assert.AreEqual("empty", actual);

            actual = WorkbookUtil.CreateSafeSheetName("1234567890123456789012345678901TOOLONG");
            Assert.AreEqual("1234567890123456789012345678901", actual);

            actual = WorkbookUtil.CreateSafeSheetName("sheet:a4");
            Assert.AreEqual("sheet a4", actual);
        }
Пример #4
0
 public void SetSheetName(int sheetIndex, string sheetname)
 {
     this.ValidateSheetIndex(sheetIndex);
     if (sheetname != null && sheetname.Length > 31)
     {
         sheetname = sheetname.Substring(0, 31);
     }
     WorkbookUtil.ValidateSheetName(sheetname);
     if (this.ContainsSheet(sheetname, sheetIndex))
     {
         throw new ArgumentException("The workbook already contains a sheet of this name");
     }
     new XSSFFormulaUtils(this).UpdateSheetName(sheetIndex, sheetname);
     this.workbook.sheets.GetSheetArray(sheetIndex).name = sheetname;
 }
Пример #5
0
        /// <summary>
        /// 创建工作表
        /// </summary>
        /// <param name="name">工作表名</param>
        /// <returns></returns>
        public IWorkSheet CreateSheet(string name)
        {
            if (name == null)
            {
                throw new ArgumentException("sheetName must not null");
            }

            if (ContainsSheet(name, Sheets.Count))
            {
                throw new ArgumentException("The workbook already contains a sheet of this name");
            }

            if (name.Length > 31)
            {
                name = name.Substring(0, MaxSensitveSheetNameLength);
            }
            WorkbookUtil.ValidateSheetName(name);

            IWorkSheet sheet = new WorkSheet();

            sheet.SheetName = name;
            Sheets.Add(sheet);
            return(sheet);
        }
Пример #6
0
        /// <summary>
        /// Creates the report.
        /// </summary>
        /// <param name="reportFacility">the result of a DPoW validation to be transformed into report form.</param>
        /// <param name="destinationStream">target stream for the spreadsheet</param>
        /// <param name="format">determines the excel format to use</param>
        /// <returns>true if successful, errors are cought and passed to Logger</returns>
        public bool Create(Facility reportFacility, Stream destinationStream, SpreadSheetFormat format)
        {
            var workBook = format == SpreadSheetFormat.Xlsx
                           // ReSharper disable once RedundantCast
                ? (IWorkbook) new XSSFWorkbook()
                           // ReSharper disable once RedundantCast
                : (IWorkbook) new HSSFWorkbook();


            var facReport = new FacilityReport(reportFacility);


            var summaryPage = workBook.CreateSheet("Summary");

            if (!CreateSummarySheet(summaryPage, reportFacility))
            {
                return(false);
            }

            // reports on Documents
            //
            if (reportFacility.Documents != null)
            {
                var documentsPage = workBook.CreateSheet("Documents");
                if (!CreateDocumentDetailsSheet(documentsPage, reportFacility.Documents))
                {
                    return(false);
                }
            }

            var iRunningWorkBook = 1;

            // reports on AssetTypes details
            //
            // ReSharper disable once LoopCanBeConvertedToQuery // might restore once code is stable
            foreach (var assetType in facReport.AssetRequirementGroups)
            {
                // only report items with any assets submitted (a different report should probably be provided otherwise)

                if (assetType.GetSubmittedAssetsCount() < 1)
                {
                    continue;
                }
                var firstOrDefault = assetType.RequirementCategories.FirstOrDefault(cat => cat.Classification == @"Uniclass2015");
                if (firstOrDefault == null)
                {
                    continue;
                }
                var tName     = firstOrDefault.Code;
                var validName = WorkbookUtil.CreateSafeSheetName(string.Format(@"{0} {1}", iRunningWorkBook++, tName));

                var detailPage = workBook.CreateSheet(validName);
                if (!CreateDetailSheet(detailPage, assetType))
                {
                    return(false);
                }
            }

            // reports on Zones details

            // ReSharper disable once LoopCanBeConvertedToQuery // might restore once code is stable
            foreach (var zoneGroup in facReport.ZoneRequirementGroups)
            {
                // only report items with any assets submitted (a different report should probably be provided otherwise)
                if (zoneGroup.GetSubmittedAssetsCount() < 1)
                {
                    continue;
                }
                var firstOrDefault = zoneGroup.RequirementCategories.FirstOrDefault(cat => cat.Classification == @"Uniclass2015");
                if (firstOrDefault == null)
                {
                    continue;
                }
                var tName     = firstOrDefault.Code;
                var validName = WorkbookUtil.CreateSafeSheetName(string.Format(@"{0} {1}", iRunningWorkBook++, tName));

                var detailPage = workBook.CreateSheet(validName);
                if (!CreateDetailSheet(detailPage, zoneGroup))
                {
                    return(false);
                }
            }
            try
            {
                workBook.Write(destinationStream);
            }
            catch (Exception ex)
            {
                Logger.LogError(0, ex, "Failed to stream excel report");
                return(false);
            }
            return(true);
        }
Пример #7
0
        public void GenerarExcel()
        {
            var NombreExcel = "Venta - Sistemas de Ventas ";

            // Recuperamos la data  de las consulta DB
            var data = (List <Annies.Entities.Ventas>)Session["ReporteVenta"];

            // Creación del libro excel xlsx.
            var wb = new XSSFWorkbook();

            // Creación del la hoja y se especifica un nombre
            var    fileName = WorkbookUtil.CreateSafeSheetName("Ventas");
            ISheet sheet    = wb.CreateSheet(fileName);

            // Contadores para filas y columnas.
            int rownum  = 0;
            int cellnum = 0;

            // Creacion del estilo de la letra para las cabeceras.
            var fontCab = wb.CreateFont();

            fontCab.FontHeightInPoints = 10;
            fontCab.FontName           = "Calibri";
            fontCab.Boldweight         = (short)FontBoldWeight.Bold;
            fontCab.Color = HSSFColor.White.Index;

            // Creacion del color del estilo.
            var colorCab = new XSSFColor(new byte[] { 7, 105, 173 });

            // Se crea el estilo y se agrega el font al estilo
            var styleCab = (XSSFCellStyle)wb.CreateCellStyle();

            styleCab.SetFont(fontCab);
            styleCab.FillForegroundXSSFColor = colorCab;
            styleCab.FillPattern             = FillPattern.SolidForeground;


            string[] Cabezeras =
            {
                "Código Venta", "Código Producto", "Marca", "Cantidad Venta", "Fecha", "Precio Final", "Talla Venta"
            };

            // Se crea la primera fila para las cabceras.
            IRow  row = sheet.CreateRow(rownum++);
            ICell cell;

            foreach (var item in Cabezeras)
            {
                // Se crea celdas y se agrega las cabeceras
                cell = row.CreateCell(cellnum++);
                cell.SetCellValue(item);
                cell.CellStyle = styleCab;

                sheet.AutoSizeColumn(cellnum);
            }

            // Creacion del estilo de la letra para la data.
            var fontBody = wb.CreateFont();

            fontBody.FontHeightInPoints = 10;
            fontBody.FontName           = "Arial";

            var styleBody = (XSSFCellStyle)wb.CreateCellStyle();

            styleBody.SetFont(fontBody);


            // Impresión de la data
            foreach (var item in data)
            {
                cellnum = 0;
                row     = sheet.CreateRow(rownum++);

                sheet.AutoSizeColumn(cellnum);
                AddValue(row, cellnum++, item.Cod_Venta.ToString(), styleBody); sheet.AutoSizeColumn(cellnum);
                AddValue(row, cellnum++, item.Producto.Cod_Prod.ToString(), styleBody); sheet.AutoSizeColumn(cellnum);
                AddValue(row, cellnum++, item.Producto.Marca_Prod.ToString(), styleBody); sheet.AutoSizeColumn(cellnum);
                AddValue(row, cellnum++, item.Cant_Venta.ToString(), styleBody); sheet.AutoSizeColumn(cellnum);
                AddValue(row, cellnum++, item.Fecha.ToString().Substring(6, 2) + "/" + item.Fecha.ToString().Substring(4, 2) + "/" + item.Fecha.ToString().Substring(0, 4), styleBody); sheet.AutoSizeColumn(cellnum);
                AddValue(row, cellnum++, item.Precio_Final.ToString(), styleBody); sheet.AutoSizeColumn(cellnum);
                AddValue(row, cellnum++, item.Talla_Venta.ToString(), styleBody); sheet.AutoSizeColumn(cellnum);
            }

            var nameFile = NombreExcel + DateTime.Now.ToString("dd_MM_yyyy HH:mm:ss") + ".xlsx";

            Response.AddHeader("content-disposition", "attachment; filename=" + nameFile);
            Response.ContentType = "application/octet-stream";
            Stream outStream = Response.OutputStream;

            wb.Write(outStream);
            outStream.Close();
            Response.End();
        }
Пример #8
0
 public void SetSheetHidden(int sheetIx, SheetState state)
 {
     this.ValidateSheetIndex(sheetIx);
     WorkbookUtil.ValidateSheetState(state);
     this.sheets[sheetIx].sheet.state = (ST_SheetState)state;
 }
Пример #9
0
        private static void AddSheet <T>(XSSFWorkbook workbook, bool setColumnWidth, Sheet <T> sheetElement)
        {
            var sheet = workbook.CreateSheet(WorkbookUtil.CreateSafeSheetName(sheetElement.Name));

            XSSFFont font = (XSSFFont)workbook.CreateFont();

            font.Boldweight = (short)FontBoldWeight.Bold;
            var boldStyle = workbook.CreateCellStyle();

            boldStyle.SetFont(font);

            var numericStyle = workbook.CreateCellStyle();

            numericStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0");

            int rowIndex    = 0;
            int columnIndex = 0;
            var row         = sheet.CreateRow(rowIndex++);

            foreach (var column in sheetElement.Columns)
            {
                var cell = row.CreateCell(columnIndex++);
                cell.SetCellValue(column.Header);
                cell.CellStyle = boldStyle;
            }

            foreach (var item in sheetElement.Data)
            {
                columnIndex = 0;
                row         = sheet.CreateRow(rowIndex++);

                foreach (var column in sheetElement.Columns)
                {
                    var cell = row.CreateCell(columnIndex++);

                    object value = column.Value(item);

                    if (value == null)
                    {
                        continue;
                    }

                    if (value is decimal)
                    {
                        cell.SetCellValue((double)(decimal)value);
                        cell.CellStyle = numericStyle;
                    }
                    else if (value is int)
                    {
                        cell.SetCellValue((double)(int)value);
                        cell.CellStyle = numericStyle;
                    }
                    else if (value is double)
                    {
                        cell.SetCellValue((double)value);
                        cell.CellStyle = numericStyle;
                    }
                    else if (value is long)
                    {
                        cell.SetCellValue((double)(long)value);
                        cell.CellStyle = numericStyle;
                    }
                    else
                    {
                        cell.SetCellValue(value.ToString());
                    }
                }
            }

            if (setColumnWidth)
            {
                for (int i = 0; i < sheetElement.Columns.Count(); i++)
                {
                    if (sheet.LastRowNum < 1000)
                    {
                        sheet.AutoSizeColumn(i); // Use only for sheets with few rows!
                        sheet.SetColumnWidth(i, Math.Min(MaximumColumnWidth, (int)(1.2 * sheet.GetColumnWidth(i))));
                    }
                    else
                    {
                        sheet.SetColumnWidth(i, 6000);
                    }
                }
            }
        }