I need to convert xlsx file to xml - c#

To do so I have used the Aspose.cells nuget package but this library is for evaluation only.
Workbook workbook = new Workbook("Book1.xlsx");
//Load your source workbook
Workbook workbook = new Workbook("Book1.xlsx");
//Save as Excel 2003 Spreadsheet XML
workbook.Save("Spreadsheet.xml");
//Save as plain XML data
XmlSaveOptions xmlSaveOptions = new XmlSaveOptions();
workbook.Save("data.xml", xmlSaveOptions);
So the library is converting like above.
but I am searching for a free library or any other method. I am doing this in C#.
So please help me with this.

Related

Specify Encoding Format when Export DataTable to Excel with Open Xml SDK in c#

I am just trying to export datatable as excel using open xml. Referred the below approach,
Export DataTable to Excel with Open Xml SDK in c#
But I couldn't specify the encoding format of the excel created. I want to save or create the excecl with UTF-Encoding-8 format.
Can some one help on how could the formatting specificed using Open XML
To save an Excel file with UTF-Encoding-8 Format you need to specify the encoding format under Tools -> Web Options -> Encoding while saving the excel file.
With OpenXML you need to create a new WebPublishing and add it to Workbook.
WebPublishing webPublishing1 = new WebPublishing(){ AllowPng = true, TargetScreenSize = TargetScreenSizeValues.Sz1024x768, CodePage = (UInt32Value)65001U };
workbook1.Append(webPublishing1);
//Where workbook1 is WorkbookPart.Workbook

Appending new cells breaks the excel file

This might be the duplicate as many posts refer to this kind of issues but I could not find an exact answer to this case.
So, what I have is an Excel file where cell "E4" contains a formula "=C4+D4". All other cells are empty, which means I cannot search or get them via OpenXml, simply because they do not exist in Xml. So in order to fill the cells "C4" and "D4" I have to create them (like this:)
var cell = new Cell(){
CellReference = new StringValue("C4"),
DataType = new EnumValue<CellValues>(CellValues.Number),
CellValue = new CellValue("123")
}
the same for cell "D4" and then append these cells to the row
row.Append(cell);
After I open the excel file it show an error "Excel found unreadable content in file.xlsx. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes."
I checked and when there is no formula in excel file the cells are appended correctly.
So my question is, using OpenXml how do I append cells in Excel file, which contains formula, so that not to break the file?
So the XML is malformed and corrupted the has file, hence the error:
Excel found unreadable content in file
To troubleshoot and fix this I suggest you compare the manually created xlsx to the programmatically created xlsx.
To do this you rename both files extensions from XLSX to ZIP > extract them to different folders > use a WinDiff tool (or better the "OpenXML SDK Productivity Tool") to compare the files.
Once you find how its malformed change your code to try and fix it up.
I solved my problem using EPPLUS
using (ExcelPackage excelPackage = new ExcelPackage(fileStream))
{
ExcelWorkbook excelWorkBook = excelPackage.Workbook;
ExcelWorksheet excelWorksheet = excelWorkBook.Worksheets.First();
excelWorksheet.Cells["C4"].Value = "123";
excelWorksheet.Cells["D4"].Value = "321";
excelPackage.SaveAs(memoryStream);
}

ClosedXML Add WorkSheet with Conditional Formatting

I am using ClosedXML to add new worksheet to existing Excel document.
It works fine for normal Excel document.
But if a excel document sheet contains conditional formatting on some cell then it throws error
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at ClosedXML.Excel.XLCFConverters.Convert(IXLConditionalFormat conditionalFormat, Int32 priority, SaveContext context)
at ClosedXML.Excel.XLWorkbook.GenerateWorksheetPartContent(WorksheetPart worksheetPart, XLWorksheet xlWorksheet, SaveContext context)
at ClosedXML.Excel.XLWorkbook.CreateParts(SpreadsheetDocument document)
at ClosedXML.Excel.XLWorkbook.CreatePackage(String filePath, SpreadsheetDocumentType spreadsheetDocumentType)
at ClosedXML.Excel.XLWorkbook.SaveAs(String file)
Below is the sample code
using (var excelDoc = new ClosedXML.Excel.XLWorkbook(strFilePath))
{
excelDoc.Worksheets.Add("New Result Sheet");
excelDoc.SaveAs(strFilePathSave);
}
Please help how to fix this issue.
XlsIO is a .NET library that reads and writes Excel 2003/2007/2010/2013/2016 files. Using XlsIO, you can add/modify a worksheet with conditional formatting very easily without issues. The whole suite of controls is available for free (commercial applications also) through the community license program if you qualify. The community license is the full product with no limitations or watermarks.
Step 1: Create a console application
Step 2: Add reference to Syncfusion.XlsIO.Base and Syncfusion.Compression.Base, you can add these reference to your project using NuGet also.
Step 3: Copy & paste the following code snippet.
The following code snippet illustrates how to add a worksheet with conditional formatting using XlsIO
using (ExcelEngine excelEngine = new ExcelEngine())
{
//Instantiate the excel application object.
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
//Open the workbook
IWorkbook workbook = application.Workbooks.Open("Input.xlsx");
(workbook.Worksheets as WorksheetsCollection).Add("NewSheet");
IWorksheet worksheet = workbook.Worksheets[1];
IConditionalFormats condition = worksheet.Range["A1"].ConditionalFormats;
IConditionalFormat condition1 = condition.AddCondition();
condition1.FormatType = ExcelCFType.CellValue;
condition1.Operator = ExcelComparisonOperator.Between;
condition1.FirstFormula = "10";
condition1.SecondFormula = "20";
condition1.BackColor = ExcelKnownColors.Red;
worksheet.Range["A1"].Number = 13;
//Save the workbook
workbook.SaveAs("AddedWorkbook.xlsx");
}
Kindly refer the sample to achieve this scenario and the sample can be downloaded from following location.
Download Demo
For further information about XlsIO, please refer our help documentation
Note: I work for Syncfusion

EPPLUS cannot delete worksheet >> "Part does not exist" (System.InvalidOperationException)

I have build an excel workbook with several worksheets as a reporting template.
The task is done by creating a new excelpackage from the designed xlsx file and fill it up with data.
The template xlsx containing charts and data worksheets.
var packageReport = new ExcelPackage();
packageReport.Load(new memoryStream(Properties.Resources.Reporting_Template));
packageReport.Workbook.Worksheets.Delete(3) // not working >> Exception
packageReport.Workbook.Worksheets.Delete(packageReport.Workbook.Worksheets["Name"]) // not working >> Exception
var ws = packageReport.Workbook.Worksheets.FirstOfDefault(w => w.Name == "Name");
packageReport.Workbook.Worksheets.Delete(ws); // Exception
Also have tried to select the worksheet in a object var before, with also no luck ... Cannot delete any of my newly created worksheets ... :(
Any idea is welcome ...
Thx. Dudes.
Current EPPlus.dll (Version: 4.0.5.0, Runtime Version: v2.0.50727)
Addition:
Also tried to use the template constructor function to generate a copy of the excel stored as a memorystream object with no luck.

Programatically Create Excel Sheets from different templates using a Addin

I am developing an Excel Addin that is able to fetch data from our database.Instead of dumping the data directly , I would like to have the data presented in a nice format. I have got our local VBA expert to develop a templates for the same since there can be multiple sheets all of which can have different formats.
It is while adding the worksheet that I am stuck at.
string TemplateFileLocation = Path.GetFullPath(fileName);
if(File.Exists(fileName))
{
Worksheet newWorkSheet = (WorkSheet)Globals.ThisAddin.Aplication.Worksheets.Add(Missing.Value,Missing.Value,1,TemplateFileLocation);
}
The code crashes while it hits this location.
The Error code returned is : 0x800A03EC
I have verified that the path to the template file is correct.
Each of these templates have only one work sheet.
You can use EPPlus
using System.IO;
using System.Reflection;
using OfficeOpenXml;
//Create a stream of .xlsx file contained within my project using reflection
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EPPlusTest.templates.VendorTemplate.xlsx");
//EPPlusTest = Namespace/Project
//templates = folder
//VendorTemplate.xlsx = file
//ExcelPackage has a constructor that only requires a stream.
ExcelPackage pck = new OfficeOpenXml.ExcelPackage(stream);

Categories

Resources