Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .xml to .xlsx how?

Tags:

c#

xml

xlsx

I want to convert a complete XML file to XLSX but I'm not sure how I can do it. I searched at Google for a Solutions but the most time I only find the way into the other direction for example XLSX to XML. On the Microsoft Page I found a xmlconvertclass, but I'm not sure how I can work with the class.

Did someone do something like this in the past and can help me?

like image 311
Fridolin Avatar asked Jul 15 '13 08:07

Fridolin


2 Answers

A far more simpler solution: use data sources in Excel.

  1. Create a "template" Xslx that matches your need.
  2. For each xml data files, add a data connection to the xml file.
  3. Set up, if you want, the data connection to refresh each time the file is opened.

This works out-of-the box, with no code at all (excluding of course the xml generation).

Optionally, you may publish your Xml through an ASP.Net application (dynamically or not), and set up the data connection to gather the data from this asp.net app.

like image 40
Steve B Avatar answered Oct 12 '22 08:10

Steve B


Try the Below code in which i converted XML into DataSet and later exported DataSet into Excel

        DataSet ds = new DataSet();

        //Convert the XML into Dataset
        ds.ReadXml(@"E:\movie.xml");

        //Retrieve the table fron Dataset
        DataTable dt = ds.Tables[0];

        // Create an Excel object
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

        //Create workbook object
        string str = @"E:\test.xlsx";
        Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(Filename: str);

        //Create worksheet object
        Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;

        // Column Headings
        int iColumn = 0;

        foreach (DataColumn c in dt.Columns)
        {
            iColumn++;
            excel.Cells[1, iColumn] = c.ColumnName;
        }

        // Row Data
        int iRow = worksheet.UsedRange.Rows.Count - 1;

        foreach (DataRow dr in dt.Rows)
        {
            iRow++;

            // Row's Cell Data
            iColumn = 0;
            foreach (DataColumn c in dt.Columns)
            {
                iColumn++;
                excel.Cells[iRow + 1, iColumn] = dr[c.ColumnName];
            }
        }

        ((Microsoft.Office.Interop.Excel._Worksheet)worksheet).Activate();

        //Save the workbook
        workbook.Save();

        //Close the Workbook
        workbook.Close();

        // Finally Quit the Application
        ((Microsoft.Office.Interop.Excel._Application)excel).Quit();
like image 136
Gun Avatar answered Oct 12 '22 09:10

Gun