Beispiel #1
9
        public void FindDateFirstLine()
        {
            string filenamePath = @"TestData\Production NALBANT Jan-Jul16 2015.xls";
            FileStream _fileStream = new FileStream(filenamePath, FileMode.Open,
                                      FileAccess.Read);

            IWorkbook _workbook = WorkbookFactory.Create(_fileStream);
            _fileStream.Close();

            //formulas of the Workbook are evaluated and an instance of a data formatter is created
            IFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(_workbook);
            DataFormatter dataFormatter = new HSSFDataFormatter(new CultureInfo("en-US"));

            // End initialize

            ISheet _worksheet = _workbook.GetSheet("Iul 2015");
            IRow firstRow = _worksheet.GetRow(0);
            int numrows = firstRow.LastCellNum;

            DateTime now = DateTime.Now;
            string result = " ";

            foreach (ICell cell in firstRow)
            {

                if (cell.StringCellValue != "")
                {
                    var Title = cell.StringCellValue;
                    var Date = Title.Substring(Title.Length - 10, 10);
                    DateTime dt = Convert.ToDateTime(Date);
                    int currentYear = now.Year;
                    int currentMonth = now.Month;
                    if (dt.Year == currentYear)
                    {
                        if (dt.Month == currentMonth)
                        {
                            result = Date;
                            break;
                        }

                    }
                }
            }

            Assert.AreEqual(result, "31.07.2015");
        }
        public ToxySpreadsheet Parse()
        {
            if (!File.Exists(Context.Path))
                throw new FileNotFoundException("File " + Context.Path + " is not found");

            bool hasHeader = false;
            if (Context.Properties.ContainsKey("HasHeader"))
            {
                hasHeader = Utility.IsTrue(Context.Properties["HasHeader"]);
            }
            bool extractHeader = false;
            if (Context.Properties.ContainsKey("ExtractSheetHeader"))
            {
                extractHeader = Utility.IsTrue(Context.Properties["ExtractSheetHeader"]);
            }
            bool extractFooter = false;
            if (Context.Properties.ContainsKey("ExtractSheetFooter"))
            {
                extractFooter = Utility.IsTrue(Context.Properties["ExtractSheetFooter"]);
            }
            bool showCalculatedResult = false;
            if (Context.Properties.ContainsKey("ShowCalculatedResult"))
            {
                showCalculatedResult = Utility.IsTrue(Context.Properties["ShowCalculatedResult"]);
            }
            bool fillBlankCells = false;
            if (Context.Properties.ContainsKey("FillBlankCells"))
            {
                fillBlankCells = Utility.IsTrue(Context.Properties["FillBlankCells"]);
            }
            bool includeComment = true;
            if (Context.Properties.ContainsKey("IncludeComments"))
            {
                includeComment = Utility.IsTrue(Context.Properties["IncludeComments"]);
            }
            ToxySpreadsheet ss = new ToxySpreadsheet();
            ss.Name = Context.Path;
            IWorkbook workbook = WorkbookFactory.Create(Context.Path);

            HSSFDataFormatter formatter = new HSSFDataFormatter();
            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                ToxyTable table = Parse(workbook, i, extractHeader, extractFooter, hasHeader, fillBlankCells, includeComment, formatter);

                ss.Tables.Add(table);
            }
            return ss;
        }
Beispiel #3
0
        private FormatBase GetFormat(double cellValue, int formatIndex, String formatStr)
        {
            FormatBase format = (FormatBase)formats[formatStr];

            if (format != null)
            {
                return(format);
            }
            if (formatStr.Equals("General"))
            {
                if (HSSFDataFormatter.IsWholeNumber(cellValue))
                {
                    return(generalWholeNumFormat);
                }
                return(generalDecimalNumFormat);
            }
            format             = CreateFormat(cellValue, formatIndex, formatStr);
            formats[formatStr] = format;
            return(format);
        }
Beispiel #4
0
        public void iterateData()
        {
            string filenamePath = @"TestData\Production NALBANT Jan-Jul16 2015.xls";
            FileStream _fileStream = new FileStream(filenamePath, FileMode.Open,
                                      FileAccess.Read);

            IWorkbook _workbook = WorkbookFactory.Create(_fileStream);
            _fileStream.Close();

            //formulas of the Workbook are evaluated and an instance of a data formatter is created
            IFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(_workbook);
            DataFormatter dataFormatter = new HSSFDataFormatter(new CultureInfo("en-US"));

            // End initialize
            ISheet _worksheet = _workbook.GetSheet("Iul 2015");
            int FirstRow = 0;
            int LastDay = 0;
            foreach (IRow row in _worksheet)
            {
                 //Index to find sheet header (first row)
                if (row.GetCell(0) != null && row.GetCell(1).NumericCellValue == 1)
                {
                    FirstRow = row.RowNum;
                    int c = 1;

                    //Index to find last column (day) with value
                    while (row.GetCell(c).NumericCellValue <= 31)
                    {
                        LastDay = row.GetCell(c).ColumnIndex;
                        if(_worksheet.GetRow(FirstRow + 24).GetCell(c).NumericCellValue == 0)
                        {
                            break;
                        }
                        c++;
                    }
                    break;
                }
            }

            DataTable results = new DataTable();
            results.Columns.Add("Date", typeof(DateTime));
            results.Columns.Add("Value", typeof(double));
            DateTime now = DateTime.Now;
            DateTime ProdDate = new DateTime(now.Year, now.Month, 1);
            DateTime InitialDate = new DateTime(now.Year, now.Month, 1);
            bool TheEnd = false;
            double Data = 0;
            //start iteration per day
            for (int day = 1; day <= LastDay; day++)
            {
                for (int hour = 1; hour <= 24; hour++)
                {
                    if (_worksheet.GetRow(FirstRow + hour).GetCell(day) == null)
                    {
                        TheEnd = true;
                        break;
                    }
                   // ProdDate = ProdDate(now.Year, now.Month, 1);
                    ProdDate = InitialDate.Date.AddDays(day - 1).AddHours(hour);
                    Data = _worksheet.GetRow(FirstRow + hour).GetCell(day).NumericCellValue;
                    results.Rows.Add(ProdDate, Data);
                }

                if (TheEnd == true)
                {
                    break;
                }

            }

                Assert.AreEqual(Data, 0.254);
        }
        public void SetUp()
        {
            // One or more test methods depends on the american culture.
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
            // create the formatter to Test
            formatter = new HSSFDataFormatter();

            // create a workbook to Test with
            wb = new HSSFWorkbook();
            ISheet sheet = wb.CreateSheet();
            IDataFormat format = wb.CreateDataFormat();

            // create a row and Put some cells in it
            IRow row = sheet.CreateRow(0);

            // date value for July 8 1901 1:19 PM
            double dateNum = 555.555;
            // date value for July 8 1901 11:23 AM
            double timeNum = 555.47431;

            //valid date formats -- all should have "Jul" in output
            String[] goodDatePatterns = {
			"[$-F800]dddd\\,\\ mmmm\\ dd\\,\\ yyyy",
			"mmm/d/yy\\ h:mm PM;@",
			"mmmm/d/yy\\ h:mm;@",
			"mmmm/d;@",
			"mmmm/d/yy;@",
			"mmm/dd/yy;@",
			"[$-409]d\\-mmm;@",
			"[$-409]d\\-mmm\\-yy;@",
			"[$-409]dd\\-mmm\\-yy;@",
			"[$-409]mmm\\-yy;@",
			"[$-409]mmmm\\-yy;@",
			"[$-409]mmmm\\ d\\,\\ yyyy;@",
			"[$-409]mmm/d/yy\\ h:mm:ss;@",
			"[$-409]mmmm/d/yy\\ h:mm:ss am;@",
			"[$-409]mmmmm;@",
			"[$-409]mmmmm\\-yy;@",
			"mmmm/d/yyyy;@",
			"[$-409]d\\-mmm\\-yyyy;@"
		};

            //valid time formats - all should have 11:23 in output
            String[] goodTimePatterns = {
		   "HH:MM",
		   "HH:MM:SS",
		   "HH:MM;HH:MM;HH:MM", 
		   // This is fun - blue if positive time,
		   //  red if negative time or green for zero!
         "[BLUE]HH:MM;[RED]HH:MM;[GREEN]HH:MM", 
		   "yyyy-mm-dd hh:mm",
         "yyyy-mm-dd hh:mm:ss",
		};

            // valid number formats
            String[] goodNumPatterns = {
				"#,##0.0000",
				"#,##0;[Red]#,##0",
				"(#,##0.00_);(#,##0.00)",
				"($#,##0.00_);[Red]($#,##0.00)",
				"$#,##0.00",
				"[$-809]#,##0.00", // international format
				"[$-2]#,##0.00", // international format
				"0000.00000%",
				"0.000E+00",
				"0.00E+00",
				"[BLACK]0.00;[COLOR 5]##.##",
		};

            // invalid date formats -- will throw exception in DecimalFormat ctor
            String[] badNumPatterns = {
				"#,#$'#0.0000",
				"'#','#ABC#0;##,##0",
				"000 '123 4'5'6 000",
				"#''0#0'1#10L16EE"
		};

            // create cells with good date patterns
            for (int i = 0; i < goodDatePatterns.Length; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dateNum);
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat(goodDatePatterns[i]));
                cell.CellStyle = (/*setter*/cellStyle);
            }
            row = sheet.CreateRow(1);

            // create cells with time patterns
            for (int i = 0; i < goodTimePatterns.Length; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(timeNum);
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat(goodTimePatterns[i]));
                cell.CellStyle = (/*setter*/cellStyle);
            }
            row = sheet.CreateRow(2);

            // create cells with num patterns
            for (int i = 0; i < goodNumPatterns.Length; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(-1234567890.12345);
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat(goodNumPatterns[i]));
                cell.CellStyle = (/*setter*/cellStyle);
            }
            row = sheet.CreateRow(3);

            // create cells with bad num patterns
            for (int i = 0; i < badNumPatterns.Length; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(1234567890.12345);
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat(badNumPatterns[i]));
                cell.CellStyle = (/*setter*/cellStyle);
            }

            // Built in formats

            { // Zip + 4 format
                row = sheet.CreateRow(4);
                ICell cell = row.CreateCell(0);
                cell.SetCellValue(123456789);
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat("00000-0000"));
                cell.CellStyle = (/*setter*/cellStyle);
            }

            { // Phone number format
                row = sheet.CreateRow(5);
                ICell cell = row.CreateCell(0);
                cell.SetCellValue(5551234567D);
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat("[<=9999999]###-####;(###) ###-####"));
                cell.CellStyle = (/*setter*/cellStyle);
            }

            { // SSN format
                row = sheet.CreateRow(6);
                ICell cell = row.CreateCell(0);
                cell.SetCellValue(444551234);
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat("000-00-0000"));
                cell.CellStyle = (/*setter*/cellStyle);
            }

            { // formula cell
                row = sheet.CreateRow(7);
                ICell cell = row.CreateCell(0);
                cell.SetCellType(CellType.FORMULA);
                cell.CellFormula = (/*setter*/"SUM(12.25,12.25)/100");
                ICellStyle cellStyle = wb.CreateCellStyle();
                cellStyle.DataFormat = (/*setter*/format.GetFormat("##.00%;"));
                cell.CellStyle = (/*setter*/cellStyle);
            }
        }
        public void TestFromFile()
        {
            IWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook("Formatting.xls");
            ISheet sheet = workbook.GetSheetAt(0);

            HSSFDataFormatter f = new HSSFDataFormatter();

            // This one is one of the nasty auto-locale changing ones...
            Assert.AreEqual("dd/mm/yyyy", sheet.GetRow(1).GetCell(0).StringCellValue);
            Assert.AreEqual("m/d/yy", sheet.GetRow(1).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("11/24/06", f.FormatCellValue(sheet.GetRow(1).GetCell(1)));

            Assert.AreEqual("yyyy/mm/dd", sheet.GetRow(2).GetCell(0).StringCellValue);
            Assert.AreEqual("yyyy/mm/dd", sheet.GetRow(2).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("2006/11/24", f.FormatCellValue(sheet.GetRow(2).GetCell(1)));

            Assert.AreEqual("yyyy-mm-dd", sheet.GetRow(3).GetCell(0).StringCellValue);
            Assert.AreEqual("yyyy\\-mm\\-dd", sheet.GetRow(3).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("2006-11-24", f.FormatCellValue(sheet.GetRow(3).GetCell(1)));

            Assert.AreEqual("yy/mm/dd", sheet.GetRow(4).GetCell(0).StringCellValue);
            Assert.AreEqual("yy/mm/dd", sheet.GetRow(4).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("06/11/24", f.FormatCellValue(sheet.GetRow(4).GetCell(1)));

            // Another builtin fun one
            Assert.AreEqual("dd/mm/yy", sheet.GetRow(5).GetCell(0).StringCellValue);
            Assert.AreEqual("d/m/yy;@", sheet.GetRow(5).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("24/11/06", f.FormatCellValue(sheet.GetRow(5).GetCell(1)));

            Assert.AreEqual("dd-mm-yy", sheet.GetRow(6).GetCell(0).StringCellValue);
            Assert.AreEqual("dd\\-mm\\-yy", sheet.GetRow(6).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("24-11-06", f.FormatCellValue(sheet.GetRow(6).GetCell(1)));


            // Another builtin fun one
            Assert.AreEqual("nn.nn", sheet.GetRow(9).GetCell(0).StringCellValue);
            Assert.AreEqual("General", sheet.GetRow(9).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("10.52", f.FormatCellValue(sheet.GetRow(9).GetCell(1)));

            // text isn't quite the format rule...
            Assert.AreEqual("nn.nnn", sheet.GetRow(10).GetCell(0).StringCellValue);
            Assert.AreEqual("0.000", sheet.GetRow(10).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("10.520", f.FormatCellValue(sheet.GetRow(10).GetCell(1)));

            // text isn't quite the format rule...
            Assert.AreEqual("nn.n", sheet.GetRow(11).GetCell(0).StringCellValue);
            Assert.AreEqual("0.0", sheet.GetRow(11).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("10.5", f.FormatCellValue(sheet.GetRow(11).GetCell(1)));

            // text isn't quite the format rule...
            Assert.AreEqual("\u00a3nn.nn", sheet.GetRow(12).GetCell(0).StringCellValue);
            Assert.AreEqual("\"\u00a3\"#,##0.00", sheet.GetRow(12).GetCell(1).CellStyle.GetDataFormatString());
            Assert.AreEqual("\u00a310.52", f.FormatCellValue(sheet.GetRow(12).GetCell(1)));
        }
        public void TestGeneralAtFormat()
        {
            IWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook("47154.xls");
            ISheet sheet = workbook.GetSheetAt(0);
            IRow row = sheet.GetRow(0);
            ICell cellA1 = row.GetCell(0);

            Assert.AreEqual(CellType.NUMERIC, cellA1.CellType);
            Assert.AreEqual(2345.0, cellA1.NumericCellValue, 0.0001);
            Assert.AreEqual("@", cellA1.CellStyle.GetDataFormatString());

            HSSFDataFormatter f = new HSSFDataFormatter();

            Assert.AreEqual("2345", f.FormatCellValue(cellA1));
        }
Beispiel #8
0
        public void iterateData()
        {
            var mockConfigProvider = new Mock<IConfigurationProvider>();
            mockConfigProvider.Setup(x => x.GetHourlyPlantsString()).Returns("MAREE01");
            mockConfigProvider.Setup(x => x.GetMeasureSourceFor1HResolution()).Returns("CLIENTE1H");
            mockConfigProvider.Setup(x => x.GetDataVariable()).Returns("E");
            mockConfigProvider.Setup(x => x.GetResolution()).Returns("1H");
            mockConfigProvider.Setup(x => x.GetEXIMToGnarumOffsetHours()).Returns(-1);
            mockConfigProvider.Setup(x => x.GetMeasureValueMultiplier()).Returns(1000);

            var apiPlant = new ApiPlant
            {
                Id = "NALBAN01",
                Technology = "EO",
                CountryCode = "ES",
                RegionCode = "28",
                TimeZone = "E. Europe Standard Time",
                Latitude = 40.4293,
                Longitude = -3.6574,
                Power = 22668
            };

            var mockPlantService = new Mock<IPlantService>();
            mockPlantService.Setup(x => x.GetPlant("NALBAN01")).Returns(apiPlant);

            string filenamePath = @"TestData\Production NALBANT Jan-Jul22 2015.xls";
            FileStream _fileStream = new FileStream(filenamePath, FileMode.Open,
                                      FileAccess.Read);

            IWorkbook _workbook = WorkbookFactory.Create(_fileStream);
            _fileStream.Close();

            //formulas of the Workbook are evaluated and an instance of a data formatter is created
            IFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(_workbook);
            DataFormatter dataFormatter = new HSSFDataFormatter(new CultureInfo("en-US"));

            MeasureFileExtracter measureFile = new MeasureFileExtracter(mockConfigProvider.Object, mockPlantService.Object);

            // End initialize
            ISheet _worksheet = _workbook.GetSheet("Iul 2015");
            int FirstRow = 0;
            int LastDay = 0;
            foreach (IRow row in _worksheet)
            {
                //Index to find sheet header (first row)
                if (row.GetCell(0) != null && row.GetCell(1).NumericCellValue == 1)
                {
                    FirstRow = row.RowNum;
                    int c = 1;

                    //Index to find last column (day) with value
                    while (row.GetCell(c).NumericCellValue <= 31)
                    {
                        LastDay = row.GetCell(c).ColumnIndex;
                        //check that there is some value for the iterated day by going to the SUM cell at the end
                        if (_worksheet.GetRow(FirstRow + 25).GetCell(c).NumericCellValue == 0)
                        {
                            break;
                        }
                        c++;
                    }
                    break;
                }
            }

            //DataTable results = new DataTable();
            //results.Columns.Add("Date", typeof(DateTime));
            //results.Columns.Add("Value", typeof(double));
            DateTime now = DateTime.Now;
            DateTime ProdDate = new DateTime(now.Year, now.Month, 1);
            DateTime InitialDate = new DateTime(now.Year, now.Month, 1);
            bool TheEnd = false;
            double Data = 0;
            var result = new List<Measure>();

            //start iteration per day
            for (int day = 1; day <= LastDay; day++)
            {
                //get every hour in the sheet
                for (int hour = 1; hour <= 24; hour++)
                {
                    //it will finish reading when a blank cell is found
                    var check = _worksheet.GetRow(FirstRow + hour).GetCell(day);

                    if (check.ToString() == "")
                    {
                        TheEnd = true;
                        break;
                    }
                    Data = _worksheet.GetRow(FirstRow + hour).GetCell(day).NumericCellValue;
                    // ProdDate = ProdDate(now.Year, now.Month, 1);
                    ProdDate = InitialDate.Date.AddDays(day - 1).AddHours(hour);
                    var measure = measureFile.ProcessLine(ProdDate, Data, apiPlant);

                    result.Add(measure);
                }

                if (TheEnd == true)
                {
                    break;
                }

            }

            Assert.AreEqual(Data, 0.254);
        }
Beispiel #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExcelExtractor"/> class.
 /// </summary>
 /// <param name="wb">The wb.</param>
 public ExcelExtractor(HSSFWorkbook wb)
     : base(wb)
 {
     this.wb = wb;
     _formatter = new HSSFDataFormatter();
 }
Beispiel #10
0
        ToxyTable Parse(IWorkbook workbook, int sheetIndex, bool extractHeader, bool extractFooter, bool hasHeader, bool fillBlankCells, bool includeComment, HSSFDataFormatter formatter)
        {
            ToxyTable table = new ToxyTable();
            if (workbook.NumberOfSheets - 1 < sheetIndex)
            {
                throw new ArgumentOutOfRangeException(string.Format("This file only contains {0} sheet(s).", workbook.NumberOfSheets));
            }
            ISheet sheet = workbook.GetSheetAt(sheetIndex);
            table.Name = sheet.SheetName;

            if (extractHeader && sheet.Header != null)
            {
                table.PageHeader = sheet.Header.Left + "|" + sheet.Header.Center + "|" + sheet.Header.Right;
            }

            if (extractFooter && sheet.Footer != null)
            {
                table.PageFooter = sheet.Footer.Left + "|" + sheet.Footer.Center + "|" + sheet.Footer.Right;
            }

            bool firstRow = true;
            table.LastRowIndex = sheet.LastRowNum;
            foreach (IRow row in sheet)
            {
                ToxyRow tr = null;
                if (!hasHeader || !firstRow)
                {
                    tr = new ToxyRow(row.RowNum);
                }
                else if (hasHeader && firstRow)
                {
                    table.HeaderRows.Add(new ToxyRow(row.RowNum));
                }
                foreach (ICell cell in row)
                {
                    if (hasHeader && firstRow)
                    {
                        table.HeaderRows[0].Cells.Add(new ToxyCell(cell.ColumnIndex, cell.ToString()));
                    }
                    else
                    {
                        if (tr.LastCellIndex < cell.ColumnIndex)
                        {
                            tr.LastCellIndex = cell.ColumnIndex;
                        }
                        ToxyCell c = new ToxyCell(cell.ColumnIndex, formatter.FormatCellValue(cell));
                        if (!string.IsNullOrEmpty(cell.ToString()))
                        {
                            tr.Cells.Add(c);
                        }
                        else if (fillBlankCells)
                        {
                            tr.Cells.Add(c);
                        }
                        if (includeComment && cell.CellComment != null)
                        {
                            c.Comment = cell.CellComment.String.String;
                        }
                    }
                }
                if (tr != null)
                {
                    tr.RowIndex = row.RowNum;
                    table.Rows.Add(tr);

                    if (table.LastColumnIndex < tr.LastCellIndex)
                        table.LastColumnIndex = tr.LastCellIndex;
                }
                if (firstRow)
                {
                    firstRow = false;
                }
            }
            for (int j = 0; j < sheet.NumMergedRegions; j++)
            {
                var range = sheet.GetMergedRegion(j);
                table.MergeCells.Add(new MergeCellRange() { FirstRow = range.FirstRow, FirstColumn = range.FirstColumn, LastRow = range.LastRow, LastColumn = range.LastColumn });
            }
            return table;
        }
Beispiel #11
0
        public ToxyTable Parse(int sheetIndex)
        {
            if (!File.Exists(Context.Path))
                throw new FileNotFoundException("File " + Context.Path + " is not found");

            bool hasHeader = false;
            if (Context.Properties.ContainsKey("HasHeader"))
            {
                hasHeader = Utility.IsTrue(Context.Properties["HasHeader"]);
            }
            bool extractHeader = false;
            if (Context.Properties.ContainsKey("ExtractSheetHeader"))
            {
                extractHeader = Utility.IsTrue(Context.Properties["ExtractSheetHeader"]);
            }
            bool extractFooter = false;
            if (Context.Properties.ContainsKey("ExtractSheetFooter"))
            {
                extractFooter = Utility.IsTrue(Context.Properties["ExtractSheetFooter"]);
            }
            bool showCalculatedResult = false;
            if (Context.Properties.ContainsKey("ShowCalculatedResult"))
            {
                showCalculatedResult = Utility.IsTrue(Context.Properties["ShowCalculatedResult"]);
            }
            bool fillBlankCells = false;
            if (Context.Properties.ContainsKey("FillBlankCells"))
            {
                fillBlankCells = Utility.IsTrue(Context.Properties["FillBlankCells"]);
            }
            bool includeComment = true;
            if (Context.Properties.ContainsKey("IncludeComments"))
            {
                includeComment = Utility.IsTrue(Context.Properties["IncludeComments"]);
            }
            IWorkbook workbook = WorkbookFactory.Create(Context.Path);

            HSSFDataFormatter formatter = new HSSFDataFormatter();
            return Parse(workbook, sheetIndex, extractHeader, extractFooter, hasHeader, fillBlankCells, includeComment, formatter);
        }
Beispiel #12
0
 /// <summary>
 /// Returns a string representation of the cell
 /// This method returns a simple representation,
 /// anthing more complex should be in user code, with
 /// knowledge of the semantics of the sheet being Processed.
 /// Formula cells return the formula string,
 /// rather than the formula result.
 /// Dates are Displayed in dd-MMM-yyyy format
 /// Errors are Displayed as #ERR&lt;errIdx&gt;
 /// </summary>
 public override String ToString()
 {
     string format = this.CellStyle.GetDataFormatString();
     HSSFDataFormatter formatter = new HSSFDataFormatter();
     return formatter.FormatCellValue(this);
 }
Beispiel #13
0
        public ToxySpreadsheet Parse()
        {
            if (!File.Exists(Context.Path))
                throw new FileNotFoundException("File " + Context.Path + " is not found");

            bool hasHeader = false;
            if (Context.Properties.ContainsKey("GenerateColumnHeader"))
            {
                hasHeader = Utility.IsTrue(Context.Properties["GenerateColumnHeader"]);
            }
            bool extractHeader = false;
            if (Context.Properties.ContainsKey("ExtractSheetHeader"))
            {
                extractHeader = Utility.IsTrue(Context.Properties["ExtractSheetHeader"]);
            }
            bool extractFooter = false;
            if (Context.Properties.ContainsKey("ExtractSheetFooter"))
            {
                extractFooter = Utility.IsTrue(Context.Properties["ExtractSheetFooter"]);
            }
            bool showCalculatedResult = false;
            if (Context.Properties.ContainsKey("ShowCalculatedResult"))
            {
                showCalculatedResult = Utility.IsTrue(Context.Properties["ShowCalculatedResult"]);
            }
            bool fillBlankCells = false;
            if (Context.Properties.ContainsKey("FillBlankCells"))
            {
                fillBlankCells = Utility.IsTrue(Context.Properties["FillBlankCells"]);
            }
            bool includeComment = true;
            if (Context.Properties.ContainsKey("IncludeComments"))
            {
                includeComment = Utility.IsTrue(Context.Properties["IncludeComments"]);
            }
            ToxySpreadsheet ss = new ToxySpreadsheet();
            ss.Name = Context.Path;
            IWorkbook workbook = WorkbookFactory.Create(Context.Path);
           
            HSSFDataFormatter formatter = new HSSFDataFormatter();
            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                ToxyTable table=new ToxyTable();
                ISheet sheet = workbook.GetSheetAt(i);
                table.Name = sheet.SheetName;
                
                if (extractHeader && sheet.Header != null)
                {
                    table.PageHeader = sheet.Header.Left + "|" + sheet.Header.Center + "|" + sheet.Header.Right;
                }

                if (extractFooter && sheet.Footer != null)
                {
                    table.PageFooter = sheet.Footer.Left + "|" + sheet.Footer.Center + "|" + sheet.Footer.Right;
                }

                bool firstRow = true;
                table.LastRowIndex = sheet.LastRowNum;
                foreach (IRow row in sheet)
                {
                    ToxyRow tr=null;
                    if (!hasHeader || !firstRow)
                    {
                        tr=new ToxyRow(row.RowNum);
                    }
                    foreach (ICell cell in row)
                    {
                        if (hasHeader&& firstRow)
                        {
                            table.ColumnHeaders.Cells.Add(new ToxyCell(cell.ColumnIndex, cell.ToString()));
                        }
                        else 
                        {
                            if (tr.LastCellIndex < cell.ColumnIndex)
                            {
                                tr.LastCellIndex = cell.ColumnIndex;
                            }
                            ToxyCell c = new ToxyCell(cell.ColumnIndex, formatter.FormatCellValue(cell));
                            if (!string.IsNullOrEmpty(cell.ToString()))
                            {
                                tr.Cells.Add(c);
                            }
                            else if (fillBlankCells)
                            {
                                tr.Cells.Add(c);
                            }
                            if (cell.CellComment != null)
                            {
                                c.Comment = cell.CellComment.String.String;
                            }
                        }
                    }
                    if (tr != null)
                    {
                        tr.RowIndex = row.RowNum;
                        table.Rows.Add(tr);
                    }
                    if (firstRow)
                    {
                        firstRow = false;
                    }
                    if(table.LastColumnIndex<tr.LastCellIndex)
                        table.LastColumnIndex=tr.LastCellIndex;
                }
                for (int j = 0; j < sheet.NumMergedRegions; j++)
                { 
                    var range = sheet.GetMergedRegion(j);
                    table.MergeCells.Add(new MergeCellRange() { FirstRow = range.FirstRow, FirstColumn = range.FirstColumn, LastRow = range.LastRow, LastColumn = range.LastColumn });
                }
                ss.Tables.Add(table);
            }
            if (workbook is XSSFWorkbook)
            {
                var props= ((XSSFWorkbook)workbook).GetProperties();

                if (props.CoreProperties != null)
                {
                    if (props.CoreProperties.Title != null)
                    {
                        ss.Properties.Add("Title", props.CoreProperties.Title );
                    }
                    else if (props.CoreProperties.Identifier != null)
                    {
                        ss.Properties.Add("Identifier", props.CoreProperties.Identifier );
                    }
                    else if (props.CoreProperties.Keywords != null)
                    {
                        ss.Properties.Add("Keywords", props.CoreProperties.Keywords);
                    }
                    else if (props.CoreProperties.Revision != null)
                    {
                        ss.Properties.Add("Revision", props.CoreProperties.Revision);
                    }
                    else if (props.CoreProperties.Subject != null)
                    {
                        ss.Properties.Add("Subject", props.CoreProperties.Subject);
                    }
                    else if (props.CoreProperties.Modified != null)
                    {
                        ss.Properties.Add("Modified", props.CoreProperties.Modified);
                    }
                    else if (props.CoreProperties.LastPrinted != null)
                    {
                        ss.Properties.Add("LastPrinted", props.CoreProperties.LastPrinted);
                    }
                    else if (props.CoreProperties.Created != null)
                    {
                        ss.Properties.Add("Created", props.CoreProperties.Created);
                    }
                    else if (props.CoreProperties.Creator != null)
                    {
                        ss.Properties.Add("Creator", props.CoreProperties.Creator);
                    }
                    else if (props.CoreProperties.Description != null)
                    {
                        ss.Properties.Add("Description", props.CoreProperties.Description);
                    }
                }
                if (props.ExtendedProperties != null && props.ExtendedProperties.props!=null)
                {
                    var extProps = props.ExtendedProperties.props.GetProperties();
                    if (extProps.Application != null)
                    {
                        ss.Properties.Add("Application", extProps.Application);
                    }
                    if (extProps.AppVersion != null)
                    {
                        ss.Properties.Add("AppVersion", extProps.AppVersion);
                    }
                    if (extProps.Characters>0)
                    {
                        ss.Properties.Add("Characters", extProps.Characters);
                    }
                    if (extProps.CharactersWithSpaces>0)
                    {
                        ss.Properties.Add("CharactersWithSpaces", extProps.CharactersWithSpaces);
                    }
                    if (extProps.Company != null)
                    {
                        ss.Properties.Add("Company", extProps.Company);
                    }
                    if (extProps.Lines > 0)
                    {
                        ss.Properties.Add("Lines", extProps.Lines);
                    }
                    if (extProps.Manager != null)
                    {
                        ss.Properties.Add("Manager", extProps.Manager);
                    }
                    if (extProps.Notes> 0)
                    {
                        ss.Properties.Add("Notes", extProps.Notes);
                    }
                    if (extProps.Pages>0)
                    {
                        ss.Properties.Add("Pages", extProps.Pages);
                    }
                    if (extProps.Paragraphs>0)
                    {
                        ss.Properties.Add("Paragraphs", extProps.Paragraphs);
                    }
                    if (extProps.Words>0)
                    {
                        ss.Properties.Add("Words", extProps.Words);
                    }
                    if (extProps.TotalTime>0)
                    {
                        ss.Properties.Add("TotalTime", extProps.TotalTime);
                    }
                }
            }
            else
            {
                //HSSFWorkbook
                var si = ((HSSFWorkbook)workbook).SummaryInformation;
                if (si != null)
                {
                    if (si.Title != null)
                    {
                        ss.Properties.Add("Title", si.Title);
                    }
                    else if (si.LastSaveDateTime != null)
                    {
                        ss.Properties.Add("LastSaveDateTime", si.LastSaveDateTime);
                    }
                    else if (si.PageCount > 0)
                    {
                        ss.Properties.Add("PageCount", si.PageCount);
                    }
                    else if (si.OSVersion > 0)
                    {
                        ss.Properties.Add("OSVersion", si.OSVersion);
                    }
                    else if (si.Security > 0)
                    {
                        ss.Properties.Add("Security", si.Security);
                    }
                    else if (si.Keywords != null)
                    {
                        ss.Properties.Add("Keywords", si.Keywords);
                    }
                    else if (si.EditTime > 0)
                    {
                        ss.Properties.Add("EditTime", si.EditTime);
                    }
                    else if (si.Subject != null)
                    {
                        ss.Properties.Add("Subject", si.Subject);
                    }
                    else if (si.CreateDateTime != null)
                    {
                        ss.Properties.Add("CreateDateTime", si.CreateDateTime);
                    }
                    else if (si.LastPrinted != null)
                    {
                        ss.Properties.Add("LastPrinted", si.LastPrinted);
                    }
                    else if (si.CharCount != null)
                    {
                        ss.Properties.Add("CharCount", si.CharCount);
                    }
                    else if (si.Author != null)
                    {
                        ss.Properties.Add("Author", si.Author);
                    }
                    else if (si.LastAuthor != null)
                    {
                        ss.Properties.Add("LastAuthor", si.LastAuthor);
                    }
                    else if (si.ApplicationName != null)
                    {
                        ss.Properties.Add("ApplicationName", si.ApplicationName);
                    }
                    else if (si.RevNumber != null)
                    {
                        ss.Properties.Add("RevNumber", si.RevNumber);
                    }
                    else if (si.Template != null)
                    {
                        ss.Properties.Add("Template", si.Template);
                    }
                }
                var dsi = ((HSSFWorkbook)workbook).DocumentSummaryInformation;
                if(dsi!=null)
                {
                    if (dsi.ByteCount > 0)
                    {
                        ss.Properties.Add("ByteCount", dsi.ByteCount);
                    }
                    else if (dsi.Company !=null)
                    {
                        ss.Properties.Add("Company", dsi.Company);
                    }
                    else if (dsi.Format>0)
                    {
                        ss.Properties.Add("Format", dsi.Format);
                    }
                    else if (dsi.LineCount!= null)
                    {
                        ss.Properties.Add("LineCount", dsi.Company);
                    }
                    else if (dsi.LinksDirty)
                    {
                        ss.Properties.Add("LinksDirty", true);
                    }
                    else if (dsi.Manager!=null)
                    {
                        ss.Properties.Add("Manager", dsi.Manager);
                    }
                    else if (dsi.NoteCount != null)
                    {
                        ss.Properties.Add("NoteCount", dsi.NoteCount);
                    }
                    else if (dsi.Scale)
                    {
                        ss.Properties.Add("Scale", dsi.Scale);
                    }
                    else if (dsi.Company != null)
                    {
                        ss.Properties.Add("Company", dsi.Company);
                    }
                    else if (dsi.MMClipCount != null)
                    {
                        ss.Properties.Add("MMClipCount", dsi.MMClipCount);
                    }
                    else if (dsi.ParCount != null)
                    {
                        ss.Properties.Add("ParCount", dsi.ParCount);
                    }
                }
            }
            return ss;
        }