Quantcast
Viewing all 637 articles
Browse latest View live

New Post: Add pictures to exists Excel file with pictures

I have fixed this problem by using 2.0.

New Post: [NPOI.XSSF.UserModel] XLSX file : repair needed when using Double in SetCellValue()

This seems to be internationalization problem. I got this work by rounding the numbers.

But maybe changing the current culture could be better solution (haven't tested)

Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

New Post: Create xlsx file from Template, but the file has some errors.

I generate files from xlsx template.In the process, I add a lot of data to the file.But some of the m are right,some of them have errors.The Excel shows the following message:Repair parts: XML error /xl/worksheets/sheet1.xml. Load error. Row 528, column 0. I have checked all the templates, there is no error in them.
_IWorkbook = new XSSFWorkbook(_ItemFileForExcel);
    XSSFSheet _XSSFSheet = null;
    string _SqlFileName = string.Empty;
    foreach (string _ItemPathForSql in _SqlList)
    {
        //取得当前Sheet的sql
        FileInfo _FileInfoForSql = new FileInfo(_ItemPathForSql);
        _SqlFileName = _FileInfoForSql.Name;

        //执行SQL
        textBox1.Text += "\r\n当前正在执行:" + _SqlFileName + "   " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
        sql = ReadSqlContext(_ItemPathForSql);
        objConnection.Open();
        SqlCommand cmd = new SqlCommand(sql, objConnection);
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = sql;
        SqlDataReader DataReader = cmd.ExecuteReader();
        System.Data.DataTable dt = ConvertDataReaderToDataTable(DataReader);
        cmd.Dispose();
        objConnection.Close();
        if (dt.Rows.Count == 0)
        {
            dt.Rows.Add(dt.NewRow());
        }
        
        _XSSFSheet = (XSSFSheet)_IWorkbook.GetSheet(_FileInfoForSql.Name.Replace(".sql", ""));
        if (_XSSFSheet == null)
        {
            _XSSFSheet = (XSSFSheet)_IWorkbook.CreateSheet(_FileInfoForSql.Name.Replace(".sql", ""));
        }
        //取得当前Sheet的数据验证
        List<XSSFDataValidation> _XSSFDataValidationList = _XSSFSheet.GetDataValidations();

        //写入数据
        FillDataFromTable(_XSSFSheet, "A9", dt);
        //设置Tab颜色
        _XSSFSheet.SetTabColor(NPOI.HSSF.Util.HSSFColor.RED.index);

        dt.Clear();
        dt.Dispose();
    }
    //写入文件
    FileStream _FileStream = File.Create(outputPath + "\\" + listProject.Text + "\\" + fileName);
    using (_FileStream)
    {
        _IWorkbook.Write(_FileStream);
        if (_FileStream.CanWrite)
        {
            _FileStream.Flush();
        }
    }

New Post: [NPOI.XSSF.UserModel] XLSX file : repair needed when using Double in SetCellValue()

Hi,

Thanks for your feedback. I will try this fix as soon as possible, but I also need to check impacts that this locale change will have on the file.

I keep you updated.

New Post: Read XLS with Protected Book and Sheet via HSSF.EventUserModel

Using the HSSF.EventUserModel, how can I read all Records (including CellRecords) for an XLS file with both Workbook and Worksheet protection?

Create Input Spreadsheet (in Excel 2010):
  1. Create new Blank workbook.
  2. Set value of A1 to number: 50
  3. Set value of A2 to string: fifty
  4. Set value of A3 to formula: =25*2
  5. Review (ribbon) -> Protect Sheet -> Password: pass1
  6. Review (ribbon) -> Protect Workbook -> Password: pass1
  7. File (ribbon) ->Save As... -> Save as type: Excel 97-2003 Workbook
Progress thus far:
  • Setting NPOI.HSSF.Record.Crypto.Biff8EncryptionKey.CurrentUserPassword = "pass1"; did not work.
  • The ProcessRecord( ) function catches a PasswordRecord (link), but I can't find any documentation on how to properly handle it.
  • Perhaps, the EncryptionInfo or Decryptor classes may be of some use.

New Post: NPOI and setCellFormula(): decimal-separator is cutoff

I've a serious problem copying this formula with NPOI 1.2.5 from one cell to another with C#:

The original cell contain this:
=IF(H21>(H23*0.9997);IF(H21<(H23*1.0003);"OK";"Errore");"Errore")
The resulting cell reports exactly this formula, but with the decimal separator stripped. So I get this:
=IF(H21>(H23*9997);IF(H21<(H23*10003);"OK";"Errore");"Errore")
This is my debugger view right after the setFormula():

Image may be NSFW.
Clik here to view.
Image


Any help would be greatly appreciated.

New Post: XSSF Performance: degrade when creating huge number of rows

Hello,

We use NPOI HSSF to make an Excel of 50K rows in 9 seconds.
But when changed to use the XSSF (IWorkbook interface), the time needed increase until 3 minutes.
Our code for both tests is the same, we only change the constructor and some type definition.

Also, it is remarkable that, the performance gets worst in time.
For 30k, it takes 25 seconds.
For 70k, it takes 4 minutes.

We need to use XSSF to support more than 65K rows.

Is there any problem with the performance for XSSF?
Why is the performance degrading when more rows are created?

[EDITED]
We have use a NPOI example to see this.
Just change the new XSSFWorkbook() to new HSSFWorkbook(), and you can see that the HSSF takes 1 second, and the XSSF takes 1 minute!!!

using System;
using System.Collections.Generic;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Diagnostics;

namespace NPOI.Examples.XSSF.SetCellValuesInXlsx
{
class Program
{
    static void Main(string[] args)
    {
        IWorkbook workbook = new XSSFWorkbook();
        ISheet sheet1 = workbook.CreateSheet("Sheet1");
        sheet1.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample");
        int x = 1;

        Debug.WriteLine("Start at " + DateTime.Now.ToString());
        for (int i = 1; i <= 30000; i++)
        {
            IRow row = sheet1.CreateRow(i);
            for (int j = 0; j < 15; j++)
            {
                row.CreateCell(j).SetCellValue(x++);
            }
        }
        Debug.WriteLine("End at " + DateTime.Now.ToString());

        FileStream sw = File.Create("test.xls");
        workbook.Write(sw);
        sw.Close();
    }
}
}


Thanks in advance!
Raúl.

New Post: XSSF Performance: degrade when creating huge number of rows

Ths is a known issue in OOXML library. Since the team is busy implementing features, the performance issue may not be fixed in 2.0.1 final release.

The main reason of the issue is because XSSF uses XmlSerializer as the serializer for OOXML document. However, XmlSerializer is not working as fast as expected. It's always slow. To fix this issue, we have to find a alternative way of serializing OOXML document.

New Post: XSSF Performance: degrade when creating huge number of rows

Thanks for your answer, tonyqus.
The software is great, but with this issue we can use it.
I wish we can use it in the future.

Regards!

New Post: 如何取得EXCEL中的TEXTBOX

Hello Tony,

thanks for your work

Any news about the TextBox control ? I saw that we can define one with HSSFTextBox, but how to link it to a cell ?

Thanks

New Post: Is there any volunteer to join me?

Hi tonyqus,

I am a programmar in C# for 5 years and I'd like to do somethine for npoi.

If there is any thing I can do to assist in feature enhancement, let me know.


email: dongyongjing@163.com

New Post: How can I obtain Scaling mode: Reduce/Enlarge printout?

HI all,
I've a problem with NPOI. I need to change the print options of my worksheet so that Openoffice can print it reading Scaling mode: Reduce/Enlarge printout (last option in the following screenshot):

Image may be NSFW.
Clik here to view.
Image


No matter what I try, I always obtain this:

Image may be NSFW.
Clik here to view.
Image

New Post: Saving large workbooks

I have the same problem :(

MemoryStream WriteToStream()
{
    //Write the stream data of workbook to the root directory
    MemoryStream file = new MemoryStream();
    hssfworkbook.Write(file);
    return file;
}
generate the error in the line:
 hssfworkbook.Write(file);
constructs the workbook but in the moment of make the write... failure!!

no way I finished building the excel?

New Post: excel data corruption

Read xlsx template , modify xlsx data, then save to excel file, and then open saved xlsx file ; Excel program will prompt repair data, opened excel file format and content have changed
 OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "excel file *.xlsm|*.xlsm";

            if (dialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            FileStream fileStream = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read);
            IWorkbook workbook = WorkbookFactory.Create(fileStream);

            ISheet ProcessSheet = workbook.GetSheet("sheet1");

            ProcessSheet.ShiftRows(9, ProcessSheet.LastRowNum, 10, true, false);

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Excel file *.xlsm|*.xlsm";
            if (saveDialog.ShowDialog() == DialogResult.Cancel)
                return;

            FileStream WirteStream = new FileStream(saveDialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
            workbook.Write(WirteStream);
            WirteStream.Close();
            fileStream.Close();

New Post: 修改xlsx文件后保存会丢失数据和格式

1读物xlsx文件或xlsm文件
2修改xlsx中的数据然后保存其他文件
3打开保存文件,Excel程序会提示:在文件中发现不可读取的内容。是否恢复此工作薄?如果信任此工作薄的来源,请选择是
4强制信任后打开,发现文件和原文件格式丢失
5上述问题再excel2003中不存在,只在excel2007存在
OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "excel file *.xlsx|*.xlsx";

            if (dialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            FileStream fileStream = new FileStream(dialog.FileName, FileMode.Open, FileAccess.Read);
            IWorkbook workbook = WorkbookFactory.Create(fileStream);

            ISheet ProcessSheet = workbook.GetSheet("sheet1");

            ProcessSheet.ShiftRows(9, ProcessSheet.LastRowNum, 10, true, false);

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Excel file *.xlsx|*.xlsx";
            if (saveDialog.ShowDialog() == DialogResult.Cancel)
                return;

            FileStream WirteStream = new FileStream(saveDialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
            workbook.Write(WirteStream);
            WirteStream.Close();
            fileStream.Close();

New Post: Worksheets right to left

Hello,

I'm using your wonderful library and I'm very pleased with it!
One little but big thing that does bother me is the lack support of RTL.
A1 is on the upper left corner while my customer wants it to be on the upper-right cornet- right to left.

I opened a discussion about that 2 years ago, was it implemented since then?
If not, can you please implement it soon? it doesn't sound like a hard thing to implement, am I right?

BTW, I wrote a small library that takes params T[] and creates a full workbook with worksheets for every T array, I implemented it using reflection and my custom ReportAttribute attribute, it is quite awesome and very easy to use.

Thanks for your wonderful library!

New Post: CreateCellComment gives System.ArgumentException: An item with the same key has already been added.

This happens only in some cells now and my template worked fine before this few weeks.
  public static void SetComment(ref ISheet w, int row, int col, string text)
    {
        try
        {
            w.GetRow(row).GetCell(col).RemoveCellComment();
        }
        catch (Exception ex) {
        }

        if (text != "")
        {

            if (col < 200)
            {
                    IDrawing d = w.CreateDrawingPatriarch();
                    IComment comment = d.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, col, row, col + 4, row + text.Split('\n').Length));
//Exception happens above
                    comment.Author = "CRM";
                    comment.String = (new HSSFRichTextString(text));
                    if (w.GetRow(row).GetCell(col) != null) w.GetRow(row).GetCell(col).CellComment = comment;
            }
        }
    }


Stack trace:

at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary
2.Add(TKey key, TValue value)
at NPOI.HSSF.Record.EscherAggregate.AddTailRecord(NoteRecord note)
at NPOI.HSSF.UserModel.HSSFComment.AfterInsert(HSSFPatriarch patriarch)
at NPOI.HSSF.UserModel.HSSFPatriarch.OnCreate(HSSFShape shape)
at NPOI.HSSF.UserModel.HSSFPatriarch.CreateComment(HSSFAnchor anchor)
at NPOI.HSSF.UserModel.HSSFPatriarch.CreateCellComment(IClientAnchor anchor)
at CashflowUpdater.XSSFProgram.SetComment(ISheet& w, Int32 row, Int32 col, String text) in


What could be wrong?

New Post: I can't get it work using VB.NET

The following code is not working:

Try

Dim workbook = New HSSFWorkbook()
Dim sheet As HSSFSheet = workbook.CreateSheet("Sheet1")
Dim row As HSSFRow = sheet.CreateRow(0)
row.CreateCell(0).SetCellValue("Cell1")
            Using ms As New MemoryStream()
                workbook.Write(ms)

                Dim saveAsFileName As String = String.Format("Export-{0:d}.xls", DateTime.Now).Replace("/", "-")


                Response.ContentType = "application/vnd.ms-excel"
                Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", saveAsFileName))
                Response.Clear()
                Response.BinaryWrite(ms.GetBuffer())
                Response.End()

            End Using
Catch ex As Exception

End Try

I am getting "ex = {Unable to evaluate expression.}"

Please help

New Post: I can't get it work using VB.NET

New Post: Getting Different Result When Running Code in Visual Studio 2012 Debugger and on Deployed Web Site

Visual Studio Express 2012 for Web. Windows Server 2008 R2. IIS 7.0.

I have code that creates an Excel workbook from the results of a SQL query and then offers to open or download the Excel file. This code works fine and creates the expected files when run in the VS debugger. However, when run on the deployed site, the file downloaded is either empty or just contains the header. Ahyone know why the code would work in debug but not on the deployed site? The code is below.
 'Libraries needed for the NPOI Excel worksheet creation
Imports NPOI.HSSF.UserModel
Imports NPOI.HSSF.UserModel.HSSFCellStyle
Imports NPOI.HPSF
Imports NPOI.HSSF.Util
Imports NPOI.POIFS.FileSystem     

Private Sub DownloadMailMerge(Optional ByVal DType As String = "Group")
        Dim strSQL As String = "", Success As Boolean, MyDataSet As DataSet, I, NLines, NCol As Integer
        Dim SheetName As String, Row As HSSFRow, ShortFileName As String
        'Create workbook
        Dim xlWorkBook = New HSSFWorkbook()
        On Error GoTo DMM_Err
        SheetName = GroupDropDownList.SelectedItem.Text
        'Create Sheets
        Dim xlWorkSheet As HSSFSheet = xlWorkBook.CreateSheet(SheetName)
        xlWorkSheet.CreateRow(0).CreateCell(0).SetCellValue("test")
        With xlWorkSheet
            If DType = "Group" Then
                Row = xlWorkSheet.CreateRow(0)
                Row.CreateCell(0).SetCellValue("Name")
                Row.CreateCell(1).SetCellValue("Addressee")
                Row.CreateCell(2).SetCellValue("Salutation")
                Row.CreateCell(3).SetCellValue("AddressLine1")
                Row.CreateCell(4).SetCellValue("AddressLine2")
                Row.CreateCell(5).SetCellValue("City")
                Row.CreateCell(6).SetCellValue("State")
                Row.CreateCell(7).SetCellValue("Zip")
                Row.CreateCell(8).SetCellValue("Region")
                Row.CreateCell(9).SetCellValue("ChaplainSINGLE")
                Row.CreateCell(10).SetCellValue("ChaplainsPLURAL")
                Row.CreateCell(11).SetCellValue("StaffSINGLE")
                Row.CreateCell(12).SetCellValue("StaffPLURAL")
                Row.CreateCell(13).SetCellValue("Facility")
                Row.CreateCell(14).SetCellValue("LastGiftDate")
                Row.CreateCell(15).SetCellValue("LastGiftFundDescription")
                'Row.CreateCell(16).SetCellValue("LastGiftAppealDescription")
                NCol = 16
            ElseIf DType = "Top" Then
                Row = xlWorkSheet.CreateRow(0)
                Row.CreateCell(0).SetCellValue("Name")
                Row.CreateCell(1).SetCellValue("Addressee")
                Row.CreateCell(2).SetCellValue("Salutation")
                Row.CreateCell(3).SetCellValue("AddressLine1")
                Row.CreateCell(4).SetCellValue("AddressLine2")
                Row.CreateCell(5).SetCellValue("City")
                Row.CreateCell(6).SetCellValue("State")
                Row.CreateCell(7).SetCellValue("Zip")
                Row.CreateCell(8).SetCellValue("Region")
                Row.CreateCell(9).SetCellValue("ChaplainSINGLE")
                Row.CreateCell(10).SetCellValue("ChaplainsPLURAL")
                Row.CreateCell(11).SetCellValue("StaffSINGLE")
                Row.CreateCell(12).SetCellValue("StaffPLURAL")
                Row.CreateCell(13).SetCellValue("Facility")
                Row.CreateCell(14).SetCellValue("Director")
                NCol = 15
            Else
            End If
            'wrap the address block
            Dim WT As HSSFCellStyle = xlWorkBook.CreateCellStyle
            WT.WrapText = True
            xlWorkSheet.SetDefaultColumnStyle(0, WT)
        End With
        If DType = "Group" Then
            'Build the query
            Dim strDate, strAmount As String
            'Build the WHERE clause for the date.
            strDate = BuildDateString()
            'Build WHERE clause for amounts for group.
            strAmount = BuildAmountString()
            'Combine the date and amount criteria into main SQL statement.
            strSQL = GetMainSQL(strDate, strAmount)
            ShortFileName = Replace(GroupDropDownList.SelectedItem.Text, " ", "") + ".xls"
        ElseIf DType = "Top" Then
            'strSQL = "SELECT Name,Addressee,Salutation,AddressLine1,AddressLine2,City,State,Zip,Region,Chaplain,Director,LastGiftFund FROM [!Extranet_Appeal_Top_Donor_v]" ' ORDER BY RECORDS_SEARCHNAME.KEY_NAME, RECORDS_SEARCHNAME.FIRST_NAME, RECORDS_SEARCHNAME.MIDDLE_NAME
            strSQL = GetTopDonorSQL()
            ShortFileName = "Top Donor.xls"
        End If
        Session("ALMMSelect") = strSQL
        Dim Name, Addressee, Salutation, AddressLine1, AddressLine2, City, State, Zip, Region, Chaplain, Chaplains, Staff, Staffs, Director, Facility, LastGiftDate, LastGiftFund, LastGiftFundID, LastGiftAppeal As String
        Dim strTmp As String = ""
        Dim II, JJ As Integer
        MyDataSet = Utilities.GetDataSet3(strSQL, Success)
        If MyDataSet.Tables(0).Rows.Count > 0 Then
            NLines = 0
            For Each dr As DataRow In MyDataSet.Tables(0).Rows
                Chaplain = "" : Chaplains = "" : Staff = "" : Staffs = ""
                Name = IIf(IsDBNull(dr("Name")), "", dr("Name"))
                Addressee = IIf(IsDBNull(dr("Addressee")), "", dr("Addressee"))
                Salutation = IIf(IsDBNull(dr("Salutation")), "", dr("Salutation"))
                AddressLine1 = IIf(IsDBNull(dr("AddressLine1")), "", dr("AddressLine1"))
                AddressLine2 = IIf(IsDBNull(dr("AddressLine2")), "", dr("AddressLine2"))
                City = IIf(IsDBNull(dr("City")), "", dr("City"))
                State = IIf(IsDBNull(dr("State")), "", dr("State"))
                Zip = IIf(IsDBNull(dr("Zip")), "", dr("Zip"))
                Region = IIf(IsDBNull(dr("Region")), "", dr("Region"))
                LastGiftFund = IIf(IsDBNull(dr("LastGiftFund")), "", dr("LastGiftFund"))
                LastGiftFundID = IIf(IsDBNull(dr("LastGiftFundID")), "", dr("LastGiftFundID"))
                strTmp = ChaplainDict(LastGiftFundID)
                If InStr(strTmp, "Chaplains") > 0 Or InStr(strTmp, " chaplains ") > 0 Then
                    Chaplains = strTmp
                ElseIf InStr(strTmp, "Chaplain") > 0 Then
                    Chaplain = strTmp
                ElseIf InStr(strTmp, " and ") > 0 Then
                    Staffs = strTmp
                Else
                    Staff = strTmp
                End If
                Facility = FacilityDict(LastGiftFundID)
                If DType = "Group" Then
                    'LastGiftAppeal = IIf(IsDBNull(dr("LastGiftAppeal")), "", dr("LastGiftAppeal"))
                    LastGiftDate = IIf(IsDBNull(dr("LastGiftDate")), "", dr("LastGiftDate"))
                ElseIf DType = "Top" Then
                    Director = IIf(IsDBNull(dr("Director")), "", dr("Director"))
                End If
                'Do Not process benevolence fund gifts
                If InStr(LCase(LastGiftFundID), "0098Ben") = 0 And InStr(LCase(LastGiftFundID), "0098PHitch") = 0 Then
                    NLines = NLines + 1
                    With xlWorkSheet
                        Row = xlWorkSheet.CreateRow(NLines)
                        Row.CreateCell(0).SetCellValue(Name)
                        'Adjust row height for number of lines in address block
                        'Row.HeightInPoints = 14 * NAddressLines
                        Row.CreateCell(1).SetCellValue(Addressee)
                        Row.CreateCell(2).SetCellValue(Salutation)
                        Row.CreateCell(3).SetCellValue(AddressLine1)
                        Row.CreateCell(4).SetCellValue(AddressLine2)
                        Row.CreateCell(5).SetCellValue(City)
                        Row.CreateCell(6).SetCellValue(State)
                        Row.CreateCell(7).SetCellValue(Zip)
                        Row.CreateCell(8).SetCellValue(Region)
                        Row.CreateCell(9).SetCellValue(Chaplain)
                        Row.CreateCell(10).SetCellValue(Chaplains)
                        Row.CreateCell(11).SetCellValue(Staff)
                        Row.CreateCell(12).SetCellValue(Staffs)
                        Row.CreateCell(13).SetCellValue(Facility)
                        If DType = "Group" Then
                            Row.CreateCell(14).SetCellValue(LastGiftDate)
                            Row.CreateCell(15).SetCellValue(LastGiftFund)
                            Row.CreateCell(16).SetCellValue(LastGiftFundID)
                            'Row.CreateCell(17).SetCellValue(LastGiftAppeal)
                        ElseIf DType = "Top" Then
                            Row.CreateCell(14).SetCellValue(Director)
                        End If
                    End With
                Else
                    'Beep()
                End If
            Next
            'Format the columns to fit (autosize)
            For I = 0 To NCol - 1
                'xlWorkSheet.SetColumnWidth(I, 20 * 256)
                xlWorkSheet.AutoSizeColumn(I)
            Next
            'Create XLS file in memory
            Dim file As New MemoryStream()
            xlWorkBook.Write(file)
            'Stream file to browser
            Response.ContentType = "application/vnd.ms-excel"
            Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", ShortFileName))
            Response.Clear()
            Response.BinaryWrite(file.GetBuffer())
            Response.End()
        End If
DMM_Exit:
        Exit Sub
DMM_Err:
        Resume Next
    End Sub
Viewing all 637 articles
Browse latest View live


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