Quantcast
Channel: npoi Discussions Rss Feed
Viewing all 637 articles
Browse latest View live

New Post: Format as Table

$
0
0
That's what I thought. I spent some time researching on poi too, but nothing came out of it.
If anybody is going through that pass, I suggest the same approach I worked on, using an Excel Macro. Any help needed with that, mail me.

Aside from that issue, NPOI has been a great tool to use when dealing with Excel. Thanks tony!

New Post: NPOI makes a mess of my .XLSX file when writing to existing file

$
0
0
Hi folks,

When I wrtie to an .XLS file there is no problem, it works correct. But when I write to a .XLSX file the file is messed up. Mu code is ±

private IWorkbook wb;

// Class and code
                FileStream file = new FileStream(bestand, FileMode.Open, FileAccess.Read);

                string ext = Path.GetExtension(bestand).ToLower();

                if (ext == ".xls")
                {
                    wb = new HSSFWorkbook(file);
                }
                else if (ext == ".xlsx")
                    wb = new XSSFWorkbook(file);

                ISheet ws = wb.GetSheet(Maanden[maand-1]); // The month sheet

                ws.GetRow(colum).GetCell(rij++).SetCellValue(huidigedatum);
                                ws.GetRow(colum).GetCell(rij++).SetCellValue(Datarow["Factuurnummer"].ToString());
                                ws.GetRow(colum).GetCell(rij++).SetCellValue(Datarow["Omschrijving"].ToString());

                                ws.GetRow(colum++).GetCell(tbBank-1).SetCellValue((double)totaal);
It this the way to write? to an .XLSX file.

Regards rinaldo

New Post: EOF In Header exception when reading .xlsm

$
0
0
I'm getting an EOF in Header exception when opening a XLSM file and initializing a XSSFWorkBook(Stream) object with the 2.0 beta version of NPOI. Below is a stack trace. Has anyone seen this before?

Stack trace:
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeByte()
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeShort()
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputBuffer.ReadLeInt()
at ICSharpCode.SharpZipLib.Zip.ZipInputStream.GetNextEntry()
at NPOI.OpenXml4Net.Util.ZipInputStreamZipEntrySource..ctor(ZipInputStream inp)
at NPOI.OpenXml4Net.OPC.ZipPackage..ctor(Stream in1, PackageAccess access)
at NPOI.OpenXml4Net.OPC.OPCPackage.Open(Stream in1)
at NPOI.Util.PackageHelper.Open(Stream is1)
at NPOI.XSSF.UserModel.XSSFWorkbook..ctor(Stream is1)
at Magnolia.FileUtilities.ExcelWrapper.openWorkbook() in C:\Development\Magnolia\Magnolia\FileUtilities\ExcelWrapper.cs:line 109
at Magnolia.FileUtilities.ExcelWrapper..ctor(String pathAndFile) in C:\Development\Magnolia\Magnolia\FileUtilities\ExcelWrapper.cs:line 91
at DocumentManager.MBGFE.ImportVBT.importVBTFile(String pathAndFile) in C:\Documents and Settings\tclaaso\my documents\visual studio 2010\Projects\DocumentManager\DocumentManager\MBGFE\ImportVBT.aspx.cs:line 454
at DocumentManager.MBGFE.ImportVBT.onImportButtonClicked(Object sender, EventArgs e) in C:\Documents and Settings\tclaaso\my documents\visual studio 2010\Projects\DocumentManager\DocumentManager\MBGFE\ImportVBT.aspx.cs:line 486

New Post: Excel Found Unreadable Content in [filename]

$
0
0
I've been struggling with this issue for a couple weeks with the NPOI 2.0 beta, where the HSSFWorkbook doesn't have the issue, but the XSSFWorkbook does, and I believe I found the source of the problem.

I found that when saving a file in XLSX format, it generated the "Excel found unreadable content" error when opening the workbook. The message was relatively benign, because it was able to open the workbook without data loss; however, it was quite annoying.

In the NPOI wrapper I use, I've always saved a file before doing any work (essentially saving a blank workbook), because I wanted to keep a placeholder. This never created a problem with the HSSFWorkbook. However, it was precisely this action that caused the error.

I changed my wrapper, and my overall strategy to not do this initial save, and that stopped the error.

I just wanted to give this as an FYI

New Post: EOF In Header exception when reading .xlsm

$
0
0
FYI - this problem was resolved, and it was a problem on my part, not on the NPOI library.

New Post: read word doc into string

New Post: WriteProtectWorkbook issue

$
0
0
Hi all,
I've created a xls file for download with:
HSSFWorkbook book = new HSSFWorkbook(file, FileMode.Open, FileAccess.Read));
and use WrireProtectWorkbook to password protect it,
and insert data into book and write to MemorySteam,
then use Response.BinaryWrite to write to the client.
If the client save the file, then open the file saved in their computer, it will ask for password.
But if I open the file directly when the browser prompt for open/save, the file will just open without asking for password.
I'm using NPOI 1.2.5(.net 2.0)
What should I do? Thanks.

New Post: Excel Found Unreadable Content in [filename]


New Post: Dose NPOI support WinRT and WindowsPhone

$
0
0
I didn't get a chance to use WinRT or WindowsPhone because I'm still using Win7. I have no answer for this. Maybe you can try to reference NPOI and write some application to test if it's supported.

New Post: NuGet package

$
0
0
Hi,

I have installed the NuGet package for version 1.2.5 into my project but I am now getting the following warning when building the project:

Found conflicts between different versions of the same dependent assembly

This is because I already use another library that has a dependency on IonicZip.dll. I believe the way to resolve this warning would be for the NPOI NuGet package to have a dependency on the DotNetZip NuGet package rather than including the IonicZip DLL directly itself. Is this something that can be done for the next release?

Paul

New Post: Change Chart Data Range

$
0
0
green_soft_group wrote:
Hi Is it posible to change chart data range? There is a chart in excel file that its data range is A1-A4. I want to change this range(e.g. A3-A10 or B3-B8). How can I do it? Thanks
Hi,
Have you implemented the function ?Now i want to know what can I do to meet the requirement?
Thanks!

New Post: XSSF issues (ShiftRows, lastRowNumber)

$
0
0
Hi everyone,

I had a long time need for such a library, and i had the luck to stumble upon this one.

I would like to share some issues, not sure if they are bugs (or features..), that might save some people some time.

1/ i use the library to clean some unwanted stuff from a sheet before opening it using oledb and dumping it to the DB. I do it by iterating over the rows and deleting the unwanted ones. I do it using shiftRows.

I began with writing a code for xls files, using HSSF, which worked perfectly.

I then just changed the sheet type to XSSF. In short, i discovered that it will only work if after each rowShift i set the ForceFormulaRecalculation to true.

2/ The lastRowNumber isnt correct. If i open the original excel file in excel, i see that the last row is row 112, but when im debugging, i get 111. Also, when i try to shift the 112 row, i get outOfBounds exception.

Im using NPOI 2.0 beta 1 (.NET Framework 4), coding in C#.

Hope it will save you some precious daylight...

Ehud.

(Post on stackOverflow - http://stackoverflow.com/questions/17763637/xssf-issues-shiftrows-lastrownumber-npoi)

New Post: EOF In Header exception when reading .xlsm

$
0
0
Hi,
how do you solve this ? I have exactly the same problem creating a XSSFWorkbook reading from stream (xlsx source):
Here I'm reading from posted file in SharePoint (properties are SPItemEventProperties). There is no problem if I return a HSSFWorkbook with the same filestream.
 Stream fileStream = null;
            HttpPostedFile postedFile = null;
            string searchForFileName = Path.GetFileName(properties.BeforeUrl);
            HttpFileCollection collection = _context.Request.Files;
            for (int i = 0; i < collection.Count; i++)
            {
                postedFile = collection[i];
                if (searchForFileName.Equals(
                  Path.GetFileName(postedFile.FileName), StringComparison.OrdinalIgnoreCase))
                {
                    fileStream = postedFile.InputStream;
                    fileStream.Position = 0;
                    byte[] fileContents = new byte[postedFile.ContentLength];
                    fileStream.Read(fileContents, 0, postedFile.ContentLength);
                }
            }

            if (postedFile.FileName.ToLowerInvariant().EndsWith("xlsx"))
            {
                return new XSSFWorkbook(fileStream);

            }

New Post: HWPF Issue

$
0
0
I am simply trying to read the text from MS Word (.doc) file using the HWPFDocument class but somehow I can not manage to get it done.As far as I know You don't have it officialy released in a library or whatever because you said it was not stable but there was a thread that I read from another user and you gave him an advice that this is actualy possible by searching in the NPOI.Scratchpad. I did find bunch of classe there and I was trying to make a proper assembly somehow but it doesn't happen.
E.g.
When I am trying to use the HWPFFileSystem it has a constructor that includes HWPFStream(par 1) but in the implementation there is no such a constructor(with one parameter).

I am wondering if you could help me.I need it for text files that contain text and text only.No tables, no nothing.

The reason that I refered to you is because the Microsoft.Office.Interop is too slow for me.

Thanks in advantage!

New Post: EOF In Header exception when reading .xlsm

$
0
0
The context for my error is different than yours - I was not trying to open a file...I was creating one.

I can say that when I initialize a XSSFWorkbook (and get the underlying filestream), I don't use Stream.Read(). Why are you pushing the stream into a byte array when you already have the stream in the postedFile.InputStream?

In any event, this version of NPOI does seem a little temperamental...it seems like the interaction between XSSFWorkbook and the FileStream is a bit fragile...

I would try to initialize the XSSFWorkbook either by removing the lines of code where you initialize the byte array and read the stream into it...or, perhaps, consider returning the XSSFWorkbook using the PathAndFile constructor -- postedFile.FileName (or whatever attribute provides the entire path of the source file)...so, for instance, return new XSSFWorkbook(postedFile.FileName).

If you're having security issues or other technical issues directly opening postedFile.FileName, you could do a File.Copy(postedFile.FileName, TARGET_LOCATION)...then return new XSSFWorkbook(TARGET_LOCATION)


Good luck.

New Post: Reading Specific Columns or other ideas?

$
0
0
If you only need the Cells from specific Columns you can try to do this:
private static List<ICell> GetSpecificColumnsCells(ISheet sheet, int fromColumn, int toColumn)
        {
            List<ICell> specificValues = new List<ICell>();

            //In here we are filtering ONLY the columns that we want
            var records = ((HSSFSheet)sheet).Sheet.GetValueRecords()
                                    .Where((v) => v.Column >= fromColumn && v.Column <= toColumn)
                                    .Select((s) => s);

            foreach (var record in records)
            {   //GetRow will never throw exception cause we are pulling the records from existing ones
                specificValues.Add(sheet.GetRow(record.Row).GetCell(record.Column));
            }

            return specificValues;
        }

New Post: How to read cell text when formula is attached to cell.

$
0
0
In that case you can go with 2 options, or either use the ICell.CachedFormulaResultType which gives you the CellType of the actual result of that Formula and then parse that or you can go with Workbook.GetCreationHelper().CreateFormulaEvaluator().EvaluateInCell(ICell) which basically evaluates the formula and replaces that with the ACTUAL Value in the cell.

If you go with the first approach, you can create an extension method and do something like :
public static object GetValue(this ICell cell, CellType cellType)
        {
            object value = null;

            switch (cellType)
            {
                case CellType.STRING:
                {
                    value = cell.StringCellValue;
                    break;
                }
                case CellType.FORMULA:
                {   //If its a Formula, get the Actual Value not the formula itself.
                    value = cell.GetValue(cell.CachedFormulaResultType);
                    break;
                }
---- rest of code

New Post: Create row and relative formula reference

$
0
0
I dont know how CopyRow actually works (internally).. cause I've implemented my own copy cell/row which works by copying a cell or row or column, to a different row and column (if you want to full code just let me know), but when it comes to update a Formula this is what I do:

To add some context, you basically would have the SourceCell from which you're copying the data and the newCell. Now, if the CellType of the cell is Formula, I do this....
--
case CellType.FORMULA:
                    {
                        var evahssfwb = HSSFEvaluationWorkbook.Create(hssfwb);
                        var tokens = FormulaParser.Parse(sourceCell.CellFormula, evahssfwb);

                        foreach (var token in tokens)
                        {
                            if (token is RefPtg)
                            {
                                var refFormula = (RefPtg)token;
                                refFormula.Row = refFormula.IsRowRelative && sourceCell.RowIndex != newCell.RowIndex ? newCell.RowIndex - (sourceCell.RowIndex - refFormula.Row) : refFormula.Row;
                                refFormula.Column = refFormula.IsColRelative && sourceCell.ColumnIndex != newCell.ColumnIndex ? newCell.ColumnIndex - (sourceCell.ColumnIndex - refFormula.Column) : refFormula.Column;
                            }

                        }
                        newCell.SetCellFormula(FormulaRenderer.ToFormulaString(evahssfwb, tokens));

                        break;
                    }
RefPtf Contains the Cell Reference of the Formulas. So basically what we are doing is getting the tokens of the sourceCell Formula, updating the row or columns according to the destination Cell (newCell) and setting that value on the newCell.

Let me know if this helps

New Post: Reading Specific Columns or other ideas?

$
0
0
You could also use Linq magic with the DataTable:
var records = from a in _dataTable.AsEnumerable()
                  where a.Field<String>("Column1") == "SomeValue"
                  select a;
I like the DataTable data structure, even if it is a little passe with some developers. And I think it lends itself quite well as a wrapper for the Excel data format (columns, rows, etc).

New Post: EOF In Header exception when reading .xlsm

$
0
0
Thank you @timclaason,
yes, you're right with the stream reading, thats the problem of code re-using. Anyway I'm trying other XSSFWorkBook() with no luck, for example this with NPOI.OpenXml4Net.OPC.OPCPackage.
try
{
    HttpPostedFile postedFile = null;
    string searchForFileName = Path.GetFileName(properties.BeforeUrl);
    HttpFileCollection collection = _context.Request.Files;
    NPOI.OpenXml4Net.OPC.OPCPackage xlsxPackage = null;

    for (int i = 0; i < collection.Count; i++)
    {
        postedFile = collection[i];
        if (searchForFileName.Equals(Path.GetFileName(postedFile.FileName), StringComparison.OrdinalIgnoreCase))
        {
            xlsxPackage = NPOI.OpenXml4Net.OPC.OPCPackage.Open(postedFile.InputStream);
        }
    }
    return new XSSFWorkbook(xlsxPackage);
}
catch (Exception ex)
{
    return null;
    throw ex;
}
I will try with other different constructors, thanks.
Viewing all 637 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>