GithubHelp home page GithubHelp logo

dotnetcore / npoi Goto Github PK

View Code? Open in Web Editor NEW
1.9K 1.9K 410.0 63.41 MB

A .NET library for reading and writing Microsoft Office binary and OOXML file formats.

License: Apache License 2.0

C# 99.66% Smalltalk 0.31% PowerShell 0.03% CoffeeScript 0.01%
excel npoi office word

npoi's People

Contributors

alexinea avatar baiyunchen avatar froggiefrog avatar gtbuchanan avatar jondavidford avatar joshcomley avatar r0bnet avatar tincann avatar yang-xiaodong avatar zlzforever avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

npoi's Issues

Setting HSSFColor via RGB Does Not Work

Hello,

With the following code, the 1st way of creating a color works but the two commented out ones do not. Am I doing something wrong?

IWorkbook workbook = new XSSFWorkbook();

var UniversalStyle = workbook.CreateCellStyle();
UniversalStyle.FillForegroundColor = HSSFColor.Automatic.Index;
UniversalStyle.FillPattern = FillPattern.NoFill;

UniversalFont = workbook.CreateFont();
UniversalFont.Color = HSSFColor.Blue.Index;
// UniversalFont.Color = new XSSFColor(new byte[3] { 65, 124, 153 }).Indexed;
// UniversalFont.Color = new XSSFColor(System.DrawingCore.Color.FromArgb(65, 124, 153)).Indexed;
UniversalStyle.SetFont(UniversalFont);

IRow row = sheet1.CreateRow(RowIndex++);
ICell test = row.CreateCell(ColIndex++);
test.CellStyle = UniversalStyle;
test.SetCellType(CellType.String);
test.SetCellValue("This should be Blue-ish");

Write to an existing excel file, while retaining it's formatting

Please how may we write to an existing excel file, while retaining it's formatting?

For example, say i have a template.xlsx, which holds all the structure and formatting required.

I make a copy of this file, then attempt to fill the new file with new data.

The process completes without errors, but I cannot see any changes to the new file.

The gist below shows my attempt.

https://gist.github.com/CharlesOkwuagwu/a9a34647070b87a86a170875a8468ced

Kindly help point out what i'm getting wrong.

Thanks.

How to read existing Word file?

using (var fs = new FileStream(newFile2, FileMode.Create, FileAccess.Write))
            {

                XWPFDocument doc = new XWPFDocument();
                var p0 = doc.CreateParagraph();
                p0.Alignment = ParagraphAlignment.CENTER;
                XWPFRun r0 = p0.CreateRun();
                r0.FontFamily = "microsoft yahei";
                r0.FontSize = 18;
                r0.IsBold = true;
                r0.SetText("This is title");
            }

Can I pass in file stream into new XWPFDocument()?

Invalid header signature

when i am trying to import data from some xls files

NPOI.POIFS.FileSystem.NotOLE2FileException: 'Invalid header signature; read 0x6320656C6261743C, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document'

AddPicture creates invalid file format on .NET Core 2.0 with v 1.0.2

I am trying to use the 1.0.2 version for .NET Core for this .AddPicture() method. I constantly get a "cannot be opened because there are problems with the contents" error any time I use the AddPicture method. If I only use text then I get the document I need. The filename and path are correct and the file size increases the proper size on the DOCX when I view the download listing. But the file never works. I have searched StackOverflow for answers but only see the same question.

`
var ms = new NpoiMemoryStream();
ms.AllowClose = false;
NPOI.XWPF.UserModel.XWPFDocument doc = new NPOI.XWPF.UserModel.XWPFDocument();
var p0 = doc.CreateParagraph();
p0.Alignment = NPOI.XWPF.UserModel.ParagraphAlignment.LEFT;
NPOI.XWPF.UserModel.XWPFRun r0 = p0.CreateRun();
r0.FontFamily = "Arial";
r0.FontSize = 12;
r0.IsBold = false;
r0.SetText("This is my paragraph");

            string filename = <my valid name>;
            string path = _env.WebRootPath + filename;
            using (Stream s = System.IO.File.OpenRead(path))
                {
                    doc.CreateParagraph().CreateRun().AddPicture(s, (int)PictureType.PNG, "logo-large.png", 400, 300);
                }

            doc.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return File(ms, "application/vnd.ms-word", id + "-ProposalExample.docx");`

新建word文档并保存到内存流,会报dispose错误

XWPFDocument doc = new XWPFDocument(); var p0 = doc.CreateParagraph(); p0.Alignment = ParagraphAlignment.LEFT; XWPFRun r0 = p0.CreateRun(); r0.FontFamily = "宋体"; r0.FontSize = 18; r0.IsBold = true; r0.SetText("未登录过学生的账号密码"); var ms=new MemoryStream(); doc.Write(ms); ms.ToArray();//此处报错
翻看代码发现,如果new XWPFDocument时候未传入流,则默认不是走流模式,保存后会Close掉。此处应该存在问题

Convert excel to PDF (in a .NET Core project)

Hello,

It is almost simular to this issue:
#20
However, Aspose.Words (or Apose.Cells) or any other lib that I try to add to my project (with nuget manager) fails to install since I was using .NET Core 1.x. Now I updated to .NET core 2.x and now nuget allows me to install them but now I get the exception:

System.TypeLoadException: 'Could not load type 'System.Drawing.FontStyle' from assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.'

When the debugger hits the line to convert.
I think this is because the nuget packages have dependencies on .NET 4.x and .NET core doesn t 'know' about them because .NET 4.X is not .NET Core.
Any solution for this you might think of?
Any help would be much appreciated since I searched on many places already.

Thanks in advance!

Wrong Local header signature: 0xE011CFD0

Wrong Local header signature: 0xE011CFD0

using (var fs = new FileStream(tfile, FileMode.Open, FileAccess.ReadWrite))
{
XWPFDocument doc = new XWPFDocument(fs);
}

is it possible for npoi to covert word to pdf

Hi:

I have a question about if is possible for npoi to covert word to pdf.
I found there seems no other third-party free library can do that,
so I hope to know if npoi can do that, and how to do.
any instruction is highly appreciated, thanks a lot.

nuget license link

When clicking on the license link in nuget,org a "page not found" is show,n. Update the license url in the csproj file

openxml4net temp files

I've recently migrated to .NET Core 2.0 from .NET Framework 4.6.2. So instead of NPOI 2.3.0 I have to use DotNetCore.NPOI. When NPOI reads workbook it creates *.tmp file in working directory and doesn't delete it after workbook is closed. Is it a bug or some additional configuration must be added to delete these files?

hot to set font size?

my code
IRow row = sheet1.CreateRow(0);
row.Height = 30 * 30;
var cell = row.CreateCell(0);

        //第一行字体
        var font = workbook.CreateFont();
        font.IsBold = true;
        font.FontHeightInPoints = (short)100;
        cell.CellStyle.SetFont(font);

why font.FontHeightInPoints = (short)100; not work

[XSSF] sheet.GetRow() method returns null

I want to get row by sheet.GetRow(i) method invoke:
for (int i = 0; i < sheet.LastRowNum; i++)
{
var currentRow = sheet.GetRow(i);
//currentRow == null
//sheet.LastRowNum > actual rows in excel
}
}

NPOI.POIFS.FileSystem.NotOLE2FileException

Good day can help me with the following error that is generated when uploading an excel file and trying to read it. in asp.net core 2.0

Where stream is of type IFormFile file ( file.OpenReadStream())

1. ---line where the error occurs--------
  var workbook = new HSSFWorkbook (stream);

2. ---line where the error occurs--------
var workbook = new XSSFWorkbook(stream);

-------------Version NPOI--------------

---------Error------------
NPOI.POIFS.FileSystem.NotOLE2FileException: 'Invalid header signature; read 0xE011BDBFEFBDBFEF, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document'

Unable to add Formula of SUM(E1:E6)

I am trying to export data to Excel and a rather simple SUM(E1:E6) fails with the error

Value cannot be null. Parameter name: stream.

IWorkbook workbook = new XSSFWorkbook();
ISheet sheet1 = workbook.CreateSheet("Project Time");

... Other numeric and textual cells fill in and work great

row = sheet1.CreateRow(RowIndex++);

var test = row.CreateCell(ColIndex++);
test.SetCellType(CellType.Formula);
test.SetCellFormula($"1 + 2 + 3 + 4 + 5 + 6"); // WORKS
test.SetCellFormula($"SUM(1 + 2 + 3 + 4 + 5 + 6)"); // FAILS
test.SetCellFormula($"SUM(E1:E6)"); // FAILS
test.SetCellFormula($"E1 + E2 + E3"); // FAILS

XSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
workbook.Write(TheStream);

So what is the trick to Formulas?

Use HSSF to CreateRow throw expection

'WorkSheet.CreateRow(1)' threw an exception of type 'System.Collections.Generic.KeyNotFoundException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146232969
HelpLink: null
InnerException: null
Message: "The given key was not present in the dictionary."
Source: "System.Collections"
StackTrace: " at System.Collections.Generic.SortedList`2.get_Item(TKey key)\r\n at Npoi.Core.HSSF.Record.Aggregates.RowRecordsAggregate.GetRow(Int32 rowIndex)\r\n at Npoi.Core.HSSF.Model.InternalSheet.AddRow(RowRecord row)\r\n at Npoi.Core.HSSF.UserModel.HSSFSheet.AddRow(HSSFRow row, Boolean addLow)\r\n at Npoi.Core.HSSF.UserModel.HSSFSheet.CreateRow(Int32 rownum)"
TargetSite: {TValue get_Item(TKey)}

Predefined type 'MarshalByRefObject' defined in multiple assemblies

After adding the DotNetCore.NPOI library to a library targeting netstandard2.0 I get the following warning when building the project:

CSC : warning CS1685: The predefined type 'MarshalByRefObject' is defined in multiple assemblies in the global alias; using definition from 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

The 'MarshalByRefObject' type seems to be defined both in netstandard, Version=2.0.0.0 as well as in System.Runtime, Version=4.2.0.0.

My .csproj looks like:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="DotNetCore.NPOI" Version="1.0.0" />
  </ItemGroup>
</Project>

Any idea what is causing this and how to resolve?

new HSSFWorkbook() throw exception.

Following code works in NPOI 2.2.4, but NPOI.Core throw exception.

var workbook = new HSSFWorkbook();

System.TypeInitializationException : The type initializer for 'Npoi.Core.HSSF.Record.DSFRecord' th
rew an exception.
---- System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictio
nary.
Stack Trace:
at Npoi.Core.HSSF.Model.InternalWorkbook.CreateWorkbook()
at Npoi.Core.HSSF.UserModel.HSSFWorkbook..ctor()

SetAutoFilter throws ArgumentNullException

For instance

ISheet sheet = workBook.CreateSheet(sheetName) as XSSFSheet;
sheet.SetAutoFilter(new NPOI.SS.Util.CellRangeAddress(0, sheet.LastRowNum, 0, propertyNames.Length - 1));

results in

Value cannot be null.
Parameter name: stream

This worked on NPOI. Please have a look at this.

在ASP.NET Core中,把XSSFWorkbook中的内容写到MemoryStream,然后试图将MemoryStream作为FileStreamResult的参数,返回给到客户端,结果失败

关键代码如下:
using (MemoryStream stream = new MemoryStream())
{
xssfWorkbook.Write(stream);
stream.Seek(0, SeekOrigin.Begin);//Error,Cannot access a closed Stream
return File(stream, "application/ms-excel", DateTime.Now.ToString() + ".xlsx");//Error
}
错误如下:
ObjectDisposedException: Cannot access a closed Stream.
System.IO.MemoryStream.CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)

这段代码其实是直接从ASP.NET移植过来的,需求是在客户端导出Excel表格。
调试发现在执行Write方法之前,MemoryStream的CanRead、CanWrite等都是true,在Write之后MemoryStream 不能执行任何读写操作,因为它已经是Closed状态,而在ASP.NET中使用NPOI(不是NPOI Core)不会出现这个问题,所以想请教是什么原因导致 MemoryStream 关闭了。

Fails on creating HSSFWorkbook from template

My code:
var templateWorkbook = new HSSFWorkbook(templateStream, true);

Exception Stack Trace:
System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'Npoi.Core.HSSF.Record.SharedFormulaRecord[]'. at Npoi.Core.HSSF.Model.RowBlocksReader..ctor(RecordStream rs) at Npoi.Core.HSSF.Model.InternalSheet..ctor(RecordStream rs) at Npoi.Core.HSSF.UserModel.HSSFWorkbook..ctor(DirectoryNode directory, Boolean preserveNodes) at Npoi.Core.HSSF.UserModel.HSSFWorkbook..ctor(Stream s, Boolean preserveNodes)

Error Getting with NuGet

when i get the package with NuGet (Install-Package DotNetCore.NPOI) i receive the error:

Attempting to gather dependency information for package 'DotNetCore.NPOI.1.0.2' with respect to project 'GetForecastEngine', targeting '.NETFramework,Version=v4.7'
Gathering dependency information took 531.82 ms
Attempting to resolve dependencies for package 'DotNetCore.NPOI.1.0.2' with DependencyBehavior 'Lowest'
Unable to resolve dependencies. 'SharpZipLib 0.86.0' is not compatible with 'DotNetCore.NPOI 1.0.2 constraint: SharpZipLib (>= 1.0.0-alpha2)'.

SheetUtil.CopyRow has bug

in SheetUtil row 186
` IRow newRow = sheet.GetRow(targetRowIndex);
IRow sourceRow = sheet.GetRow(sourceRowIndex);

        // If the row exist in destination, push down all rows by 1 else create a new row
        if (newRow != null)
        {
            sheet.ShiftRows(targetRowIndex, sheet.LastRowNum, 1);
        }
        else
        {
            newRow = sheet.CreateRow(targetRowIndex);
        }`

Should be
` if (newRow != null)
{

            sheet.ShiftRows(targetRowIndex, sheet.LastRowNum, 1);

            newRow = sheet.GetRow(targetRowIndex);
        }`

貌似没有实现SXSSFWorkbook这个类

这是poi针对大数据量导出优化的类 HSSFWorkbook虽然省内存但是有6w行限制 XSSFWorkbook又太占内存 之前在.net framework上做的项目想移植下 看到npoi有core版很高兴 但是今天一看发现并没有SXSSFWorkbook这个类 不知道大牛可以实现不

读取word异常

用XWPFDocument加载word文档时报错:
System.Xml.XmlException: The ':' character, hexadecimal value 0x3A, cannot be included in a name。
还没试过原始版本的NPOI。

GridLines printing is being set

When I save a workbook I noticed that the print gridlines option is being set without ever being modified by the program. I traced the problem to how the printOptions (CT_PrintOptions) records is being output.
The generated record is:

<printOptions horizontalCentered="1" verticalCentered="0" headings="0" gridLines="0" gridLinesSet="0"/>

Which Excel 2016 interprets as the option being set (I assume that it is a default value of gridLines when gridLinesSet is 0). If I set gridLinesSet to 1, then it work alright.

<printOptions horizontalCentered="1" verticalCentered="0" headings="0" gridLines="0" gridLinesSet="1"/>

By the way, the equivalent record generated by Excel is much smaller because default values are not saved:

<printOptions horizontalCentered="1"/>

new XSSFWorkbook(FileStream) fails with ICSharpCode.SharpZipLib.Zip.ZipException: 'EOF in header'

Here is the code I'm using:

{
    var Excel = new XSSFWorkbook(outputStream);

    if (Debug)
    {
        var i = 0;
        while (i < Excel.NumberOfSheets)
        {
            Console.WriteLine("Found sheet: " + Excel.GetSheetName(i));
            i++;
        }
    }

    ISheet Sheet = Excel.GetSheetAt(0);

    var row = Sheet.GetRow(0);
    var cell = row.GetCell(0);

    cell.SetCellValue("test123");

                    
    Excel.Write(outputStream);
    Excel.Close();
}

This fails with ICSharpCode.SharpZipLib.Zip.ZipException: 'EOF in header' on var Excel = new XSSFWorkbook(outputStream);.

Now var Excel = new XSSFWorkbook(SourceFile); does work, but then I can't save to the same file as I'm opening, because the file will be in use.

Cell Formula

Hi,
When I set the cell Formula, an exception arise: "System.ArgumentNullException: 'Value cannot be null.'"

formula = "SUM(" + range.FormatAsString() + ")";
cell.SetCellType(CellType.Formula);
cell.CellFormula = formula;

StackTrace "
at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)\r\n
at NPOI.SS.Formula.Function.FunctionMetadataReader.CreateRegistry()\r\n
at NPOI.SS.Formula.Function.FunctionMetadataRegistry.GetInstance()\r\n
at NPOI.SS.Formula.Function.FunctionMetadataRegistry.LookupIndexByName(String name)\r\n
at NPOI.SS.Formula.PTG.AbstractFunctionPtg.IsBuiltInFunctionName(String name)\r\n
at NPOI.SS.Formula.FormulaParser.Function(String name)\r\n
at NPOI.SS.Formula.FormulaParser.ParseRangeExpression()\r\n
at NPOI.SS.Formula.FormulaParser.PercentFactor()\r\n
at NPOI.SS.Formula.FormulaParser.PowerFactor()\r\n
at NPOI.SS.Formula.FormulaParser.Term()\r\n
at NPOI.SS.Formula.FormulaParser.AdditiveExpression()\r\n
at NPOI.SS.Formula.FormulaParser.ConcatExpression()\r\n
at NPOI.SS.Formula.FormulaParser.ComparisonExpression()\r\n
at NPOI.SS.Formula.FormulaParser.UnionExpression()\r\n
at NPOI.SS.Formula.FormulaParser.Parse()\r\n
at NPOI.SS.Formula.FormulaParser.Parse(String formula, IFormulaParsingWorkbook workbook, FormulaType formulaType, Int32 sheetIndex)\r\n
at NPOI.XSSF.UserModel.XSSFCell.SetFormula(String formula, FormulaType formulaType)\r\n

Any help??

利用模板导出之后的Excel文件有问题

存在一个Excel模板:"模板.xlsx",打开没有任何问题,但是用NPOI.Core导出成另一个Excel文件之后打开就会报一个问题:
发现”XXXXX.xlsx"中的部分内容有问题。是否让我们尽量尝试恢复。如果您信任此工作簿的源,请点击是
点击是之后excel可以打开,插入的数据也都在

  var newFile = "E:/" + Guid.NewGuid().ToString() + ".xlsx";
  using (var fs = new FileStream(newFile, FileMode.Create, FileAccess.Write))
  {
      //excelPath-模板路径,为传递过来的参数
      IWorkbook wb = new XSSFWorkbook(excelPath);

      ISheet sheet1 = wb.GetSheetAt(0);
      
      //celldata-需要插入的数据,参数          
      foreach (var x in celldata)
      {
          IRow row = sheet1.GetRow(x.Cell);
          row.GetCell(x.Cell).SetCellValue(x.Value);
      }
      wb.Write(fs);
  }

无法导入.xls格式的文件

System.InvalidCastException:“Unable to cast object of type 'System.Object[]' to type 'Npoi.Core.HSSF.Record.ExternalNameRecord[]'.”

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.