Quantcast
Channel: ClosedXML - The easy way to OpenXML
Viewing all 1877 articles
Browse latest View live

New Post: Cells.InsertDataTable Time values are recognized as String

$
0
0
I appreciate your response but not exactly what i am looking for. Aligning the texts to the right will simply have no difference. columns 18-23 are time values and what I want is that when it is inside the cells, it has a formula i.e.

when hours > 24, the formula will be 1/(2++)/1900 then the time.

but if hours < 24, only the time will be idsplayed in the formula. no date of 1/1/1900.


roberttanenbaum wrote:
If you want to align the values in those columns to the right, choose columns 18 through 23 and do the following
worksheet.Columns(18,23).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;

New Post: Word generator

$
0
0
Dear all,

Thanks a lot for this great API to generate xlsx.

Now I am looking to do the same with Word document.
I 'd like to generate reporting .docx

Does somebody has an Idea for that?

Best Regards,
Youssef

New Post: Cells.InsertDataTable Time values are recognized as String

$
0
0
I managed to find the solution to my query. But I did not utilize anymore the Cell.InsertData property. What I did was to parse each and every cell according to its data type before assigning it to a particular Excel cell.

For the time values, I used regular expressions to match, then used the boolean variable to parse and set the data type of the cell to either TimeSpan or DateTime depending on what I need.
 public void DataTableToExcel(DataTable dt, string usertemplate, string exceltab)
            {

            //open worksheet
            var workbook = new XLWorkbook(usertemplate);
            var worksheet = workbook.Worksheet(exceltab);

            //declare variables
            int totrow = dt.Rows.Count;
            int totcol = dt.Columns.Count;
            int numval;
            double dobval;
            DateTime dateval;
            TimeSpan timeval;

            //loop through each cells

                for (int i = 0; i < totrow; i++)
                    {
                    DataRow dataRow = dt.Rows[i];

                    for (int j = 0; j < dataRow.Table.Columns.Count; j++)
                        {
                        #region Regex 0:00:00
                        string input = dataRow[j].ToString();
                        string pattern = "^\\d{1}:\\d{2}:\\d{2}";
                        Match match = Regex.Match(input, pattern);
                        bool match1;
                        if (match.Success)
                            {
                            match1 = true;
                            }
                        else
                            {
                            match1 = false;
                            }
                        #endregion

                        #region Regex 00:00:00
                        string input2 = dataRow[j].ToString();
                        string pattern2 = "^\\d{2}:\\d{2}:\\d{2}";
                        Match match2 = Regex.Match(input2, pattern2);
                        bool match3;
                        if (match2.Success)
                            {
                            match3 = true;
                            }
                        else
                            {
                            match3 = false;
                            }
                        #endregion

                        if (int.TryParse(dataRow[j].ToString(), out numval))
                            {
                            var cell = worksheet.Cell(i+2, j + 1);
                            cell.Value = dataRow[j].ToString();
                            cell.DataType = XLCellValues.Number;
                            }
                        else if (double.TryParse(dataRow[j].ToString(), out dobval))
                            {
                            var cell = worksheet.Cell(i+2, j + 1);
                            cell.Value = dataRow[j].ToString();
                            cell.DataType = XLCellValues.Number;
                            }
                        else if (TimeSpan.TryParse(dt.Rows[i].ToString(), out timeval))
                            {
                            var cell = worksheet.Cell(i+2, j + 1);
                            cell.Value = dataRow[j].ToString();
                            cell.DataType = XLCellValues.TimeSpan;
                            continue;
                            }
                        else if (match1 == true) //0:00:00
                            {
                            string[] timeval1 = dataRow[j].ToString().Split(':');
                            TimeSpan t = new TimeSpan(Convert.ToInt16(timeval1[0].ToString()), Convert.ToInt16(timeval1[1].ToString()), Convert.ToInt16(timeval1[2].ToString()));
                            var cell = worksheet.Cell(i+2, j + 1);
                            cell.Value = t.ToString();
                            cell.DataType = XLCellValues.TimeSpan;
                            match1 = false;
                            }
                        else if (match3 == true) //00:00:00
                            {
                            string[] timeval1 = dataRow[j].ToString().Split(':');
                            int hour = Convert.ToInt16(timeval1[0].ToString());

                            if (hour <= 23)
                                {
                                TimeSpan t = new TimeSpan(Convert.ToInt16(timeval1[0].ToString()), Convert.ToInt16(timeval1[1].ToString()), Convert.ToInt16(timeval1[2].ToString()));
                                var cell = worksheet.Cell(i + 2, j + 1);
                                cell.Value = t.ToString();
                                cell.DataType = XLCellValues.TimeSpan;
                                }
                            else
                                {
                                WeirdDateTime d = new WeirdDateTime();
                                d = d.Parse(dataRow[j].ToString());
                                object a = d.ReturnValue;
                                var cell = worksheet.Cell(i + 2, j + 1);
                                cell.Value = a.ToString();
                                cell.DataType = XLCellValues.DateTime;
                                cell.Style.NumberFormat.NumberFormatId = 46;
                                }

                            match3 = false;
                            }
                        else if (DateTime.TryParse(dataRow[j].ToString(), out dateval))
                            {
                            var cell = worksheet.Cell(i + 2, j + 1);
                            cell.Value = dataRow[j].ToString();
                            cell.DataType = XLCellValues.DateTime;
                            }
                        else
                            {
                            var cell = worksheet.Cell(i+2, j + 1);
                            cell.Value = dataRow[j].ToString();
                            cell.DataType = XLCellValues.Text;
                            }
                        }
                    }

            workbook.Save();
            }

New Post: How do I send data to excel and then refresh aspx page?

$
0
0
Russ, there may be some javascript functions that could be set up to intercept the file download response and do both the download and refresh or redirect the screen after the download completes. But I have to say that in all my time using the web, I don't recall any time where a file was downloaded and then I got redirected to another page.

However, you might be able to do what you ask by saving the file locally (either synchronously or asynchronously), returning a refresh or redirect command and then doing the download from the redirected screen. Though this would leave the file on the server.

New Post: How do I send data to excel and then refresh aspx page?

$
0
0
I just resolved it. Not sure if this is the best way, but it works.

First ... I created a new page that will save the data to the excel in the page load.

Second ... I save my data to a session variable ... Session("dataTableToExcel") = datatable

Then I call a subroutine that will open a new page in a new window ... OpenNewWindow("\DisplayExcel.aspx")
 Protected Sub OpenNewWindow(ByVal url As String)
        Dim sw As StringWriter = New StringWriter
        sw.WriteLine("<script language=""javascript"">")
        sw.WriteLine("var newWindow = window.open(""{0}"",""SendToExcel""", url)
        sw.Write(",""height=700,width=900,resizable=yes,scrollbars=yes,toolbar=no,menubar=no"");")
        sw.WriteLine("newWindow.focus();")
        sw.WriteLine("</script>")
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "Open New Window", sw.ToString())
    End Sub
The new page looks like this ....

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Dim dt As DataTable = Session("dataTableToExcel")

            Dim wb As New ClosedXML.Excel.XLWorkbook()
            wb.Worksheets.Add(dt, dt.TableName.ToString)
            Response.Clear()
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            Response.AddHeader("content-disposition", "attachment;filename=DelegateRecordsNotImported.xlsx")

            Using memoryStream As New MemoryStream()
                wb.SaveAs(memoryStream)
                Response.AddHeader("Content-Length", memoryStream.Length.ToString())

                memoryStream.WriteTo(Response.OutputStream)
                memoryStream.Close()

            End Using
        Catch ex As Exception
            Throw
        End Try
    End Sub

New Post: How do I send data to excel and then refresh aspx page?

$
0
0
Russ, glad you found a way to do it. I have a few comments on using session variables for this type of thing.
  1. Generally it is advised to not use session variables for very large amounts of data, but if you know that your data table is relatively small, it's ok to do it temporarily.
  2. Be sure you remove the session variable after you add it to the Excel file by doing Session.Remove("dataTableToExcel") or Session.RemoveAll().
  3. I have run into major problems using session variables for page related data, because if you user opens a new tab and goes back to the original page a new dataTableToExcel variable will be placed in the session variable and overwrite the original data. It is possible that the action in one browser tab would corrupt the data stored by the other browser tab just when it is being read into the Excel file. You would end up with rare cases of data corruption that disappear when they rerun it, and it is very hard to debug things like that.

New Post: How do I send data to excel and then refresh aspx page?

$
0
0
Robert,
Thanks for your input. Shortly after I posted this I did just what you said.
 Dim dt As DataTable = Session("dataTableToExcel")
 Session.Remove("dataTableToExcel")
This does two things ...
 1. It removes the data right away.  I will not be needing it after I download it to excel.
 2. Since I remove it right after I created it, the user never has a chance to create a new tab between the time I create it, use it, and then remove it.    
My data is not very large, and should never really be. This is an in-house (intranet) application so we do have somewhat more control over how our users use this page.


Thanks again for your feed back.

New Post: How to use closed xml to create excel file ?

$
0
0
Hello People, I searched in web and i got to tht openxml-sdk helps us to create excel file and also i found closed xml makes it simpler. But i couldn't find how to use the simple way (closed xml) .

What i did- 1) created a asp.net project with jqgrid (exporting to excel remains)
2) Downloaded the closed xml file (to create the excel file)

My Doubts - 1) Should i install Open xml sdk to use closed xml? 2) How to use the "Closedxml.dll" and "Closedxml" i mean where to add these file in my project to create excel file?

Created Unassigned: Syntax Error with VLookUp and/or Concatenate [9174]

$
0
0
Hi,

I've been using ClosedXML to read an Excel file (2010 version), and I get an error while reading the content of a cell containing this formula :

In Excel (french version) :
=RECHERCHEV(CONCATENER(D2;"-";F2;"-";H2;"-";I2;"-";J2;"-";K2);Buy!$A:$S;17;0)

In Visual Studio :
?oSht.Cell(idxRow, 12).FormulaA1
"VLOOKUP(CONCATENATE(D2,"-",F2,"-",H2,"-",I2,"-",J2,"-",K2),Buy!$A:$S,17,0)"

When I try to read the cell value, I get an error.

The error returned is this one : "Syntax Error" with no more comments.

The stack trace is :

à ClosedXML.Excel.CalcEngine.CalcEngine.Throw(String msg)
à ClosedXML.Excel.CalcEngine.CalcEngine.Throw()
à ClosedXML.Excel.CalcEngine.CalcEngine.Parse(String expression)
à ClosedXML.Excel.CalcEngine.ExpressionCache.get_Item(String expression)
à ClosedXML.Excel.CalcEngine.CalcEngine.Evaluate(String expression)
à ClosedXML.Excel.XLWorksheet.Evaluate(String expression)
à ClosedXML.Excel.XLCell.get_Value()

HResult : -2146233088

Is there a known problem with the VLOOKUP function, or CONCATENATE ?

Thanks in advance for your help

Damien

New Post: Iphone-Ipad cant open genereted files

$
0
0
Hi, I have this issue now. Has anyone found a fix?

New Post: Getting count of Rows in column

$
0
0
Is there a method to use to obtain the count of rows in a column? If so, what is the best approach?

I am working to read a column and then add a formula to each row in the next column but need to know how many rows to run through.

New Post: Getting count of Rows in column

$
0
0
A column doesn't have "rows", it has cells. You can simply do range.Column(1).Cells().Count()
You can even skip the column and ask for the rows in the range: range.Rows().Count()

Created Unassigned: Inserting textbox and images in a worksheet [9180]

$
0
0
Hi, I need to insert a textbox or an image in a worksheet, not in header or footer.

New Post: How to use closed xml to create excel file ?

$
0
0
1) Yes. the open xml sdk 2.0 needs to either be installed on the system where you test or deploy your application, or it needs to be referenced as part of the project and marked as Copy Local = True
2) ClosedXML should be referenced in your project and marked as Copy Local = True. You can put the closedxml.dll as part of the project area or elsewhere as long as it is referenced and marked Copy Local = True which will make it part of the delivered code set.

New Post: Memory problem with ClosedXML

$
0
0
I'm having a similar problem with memory not being de-allocated when the workbook/worksheet are disposed.
I have created a datatable and am creating a workbook/worksheet directly from it:
 Try
            Dim WorkBook As XLWorkbook = New XLWorkbook()
            WorkBook.CalculateMode = XLCalculateMode.Manual
            Dim WorkSheet As IXLWorksheet = WorkBook.Worksheets.Add(SheetName)
            WorkSheet.Cell(1, 1).InsertTable(Datatbl.AsEnumerable())            'insert the entire datatable
            WorkBook.SaveAs(XLSPathFileName)
            WorkSheet.Dispose()
            WorkBook.Dispose()
        Catch ex As Exception
            LOG("CreateXLS error: " & ex.Message)
        End Try
After this has completed, the workbook/worksheet look great but it leaves me with over 150 MB of allocated memory when the application usually has about 15MB prior to workbook creation. I also dispose the datatable right afterwards as well.
Any advice on how I can release this memory?
Thanks,
Rusty

New Post: How to Export Excel File as a Zip File

$
0
0
I just wanted to know if it's possible to export a Zip package that contains an Excel file created by ClosedXML.

I've been able to successfully export my data to just Excel using your documentation page titled "How do I deliver an Excel file in ASP.NET."

However I am trying to package my Excel file with a PowerPoint file into a Zip package. Unfortunately my Excel file in the zip package has an error message when I try to open it that says "Excel cannot open the file 'NewPresentation.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file." The PowerPoint file was able to export fine.

I've tried 2 separate functions and was unsuccessful in both. Any help would be greatly appreciated. Thank you.

Steve
public void StreamZipNEW(Dictionary<int, MemoryStream> reportStreams, ExcelClosedXML excelClosedXML, string destPPTXFile, string destXLSXFile, string fileName)
        {
            MemoryStream outputStream = new MemoryStream();

            reportStreams[0].Position = 0; //PowerPoint
            reportStreams[1] = new MemoryStream(); //Excel
            reportStreams[1].Position = 0;

            Telerik.Web.Zip.ZipPackage zipPackage = Telerik.Web.Zip.ZipPackage.Create(outputStream);

            zipPackage.AddStream(reportStreams[0], destPPTXFile);
            zipPackage.AddStream(reportStreams[1], destXLSXFile);

            string destFile = string.Format("{0}.zip", fileName);
            zipPackage.Close(false);
            outputStream.Position = 0;
            if (outputStream != null && outputStream.Length > 0)
            {
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment; filename=\"" + destFile);
                Response.ContentType = "application/zip";
                Response.BufferOutput = false;   // to prevent buffering
                byte[] buffer = new byte[1024];
                int bytesRead = 0;

                excelClosedXML.XLWorkbook.SaveAs(reportStreams[1]);

                while ((bytesRead = outputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    Response.OutputStream.Write(buffer, 0, bytesRead);
                }

                Response.End();
            }
            outputStream.Close();

        }
public void StreamZipNEW2(Dictionary<int, MemoryStream> reportStreams, ExcelClosedXML excelClosedXML, string destPPTXFile, string destXLSXFile, string fileName)
        {
            MemoryStream outputStream = new MemoryStream();
            string destFile = string.Format("{0}.zip", fileName);

            HttpResponse httpResponse = Response;
            httpResponse.Clear();

            Telerik.Web.Zip.ZipPackage zipPackage = Telerik.Web.Zip.ZipPackage.Create(outputStream);

            excelClosedXML.XLWorkbook.SaveAs(reportStreams[1]);

            zipPackage.AddStream(reportStreams[0], destPPTXFile); //PowerPoint
            zipPackage.AddStream(reportStreams[1], destXLSXFile); //Excel

            zipPackage.Close(false);
            
            httpResponse.ContentType = "application/zip";
            httpResponse.AddHeader("content-disposition", string.Format("attachment;filename=\"{0}\"", destFile));
            outputStream.WriteTo(httpResponse.OutputStream);
            outputStream.Close();

            httpResponse.End();
        }

New Post: Iphone-Ipad cant open genereted files

$
0
0
Hi, I have this issue too.
Has anyone found a fix?

New Post: PAGE BREAKS

$
0
0
I want to add Page Breaks and change some data in the header with each new page.
The page break works fine, but I couldn't change the header to write the new text that forced the break.

Thank you.

New Post: Export Oracle SQL query result in to Excel

$
0
0
I am trying to create a very simple WPF application on .Net 4.0 using C# and Oracle as a backend database. Everything works fine, i can pull the data I want (using oracle sql queries)from the database and fill the UI DataGrid. But,

1) I am trying to see that If it is possible to dump(export) the entire result in to an excel work sheet(created using ClosedXML).

2) I would want to name the work sheet, a value of a particular cell from the result.

Please advise. Thanks!!

New Post: AutoFit Row Height

$
0
0
Hello Sir,

How to apply AutoFit Row height property in open and closed xml excel file cell.

Thanks and Regards,
Sumanth D
Viewing all 1877 articles
Browse latest View live


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