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
Related
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.
I want to read data from excel using EEPLUS in C#. Who can teach me or share the link to teach it? Thanks for reading!
It is really easy to use, just read through the GetStarted of their GitHub.
Example:
//Open the workbook (or create it if it doesn't exist)
var fi=new FileInfo(#"c:\workbooks\myworkbook.xlsx")
using (var p = new ExcelPackage(fi))
{
//Get the Worksheet created in the previous codesample.
var ws=p.Workbook.Worksheets["MySheet"];
Set the cell value using row and column.
ws.Cells[2, 1].Value = "This is cell A2. It is set to bolds";
//The style object is used to access most cells formatting and styles.
ws.Cells[2, 1].Style.Font.Bold=true;
//Save and close the package.
p.Save();
}
Using ClosedXML (v0.93.1) on .Net Core 2.0, attempting to save a workbook so that when opened it prompts the user to open as "Read Only" or enter the protected password. (See linked question below).
I have seen IXLWorksheet.Protect() and XLWorkbook.Protect() - these correctly protect the workbook but still default the user to open with R/W access. This is a problem because it write locks the file and my process can't overwrite it until the user closes excel.
This question indicates OpenXML (the underlying API for ClosedXML) has the ability to set this when saving a workbook, however ClosedXML XLWorkbook.SaveAs(SaveOptions) doesn't include this. Perhaps I can't find the closedxml documentation on this option, but I believe this is the option I need.
According to this answer and the attached github/MSDN links OpenXML doesn't support password protecting but I don't see any info about readonly open other than the first linked question saying it should be possible.
Code example:
XLWorkbook wb = new XLWorkbook();
var ws = wb.AddWorksheet("My Sheet");
// ... add to worksheet
ws.Protect("my-worksheet-password");
wb.SaveAs("C:\\my-workbook.xlsx", new SaveOptions { /* In OpenXML the option would exist during this save step. */ });
This feature is not supported by ClosedXML yet, but you can use OpenXml directly to set the require property. Refer to https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.spreadsheet.filesharing.readonlyrecommended?view=openxml-2.8.1
private void GeneratePartContent(WorkbookPart part)
{
FileSharing fileSharing1 = new FileSharing(){ ReadOnlyRecommended = true };
workbook1.Append(fileSharing1);
part.Workbook = workbook1;
}
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.
I am using closedXML to generate an Excel file from C# and I am trying to see if there is anyway to set the zoom level of a worksheet. I can't find this in any of the documentation or from googling?
Does anybody know how to do this?
It's now possible, starting with ClosedXML version 0.87.0, via the IXLSheetView.ZoomScale property.
using Excel = ClosedXML.Excel;
var wb = new Excel.XLWorkbook();
Excel.IXLWorksheet ws = wb.AddWorksheet("zoom");
Excel.IXLSheetView view = ws.SheetView;
/* Value can be set between 10 and 400 */
view.ZoomScale = 85;
You can check the IXLSheetView source code for more information.
Update for version 0.87+: https://stackoverflow.com/a/52755386/2610249
No, ClosedXML does not support setting the zoom. The option that johny links to is only for scaling of the pages when printing.
There is a feature request on the ClosedXML page, but no answer from the developer.
As previously answered, you can't, but I've found a way around it which works well:
Create a template Excel file in advance, with all sheets' zoom levels set to how you want them.
When you create your workbook, instead of:
public XLWorkbook CreateWorkbook()
{
XLWorkbook workbook = new XLWorkbook();
IXLWorksheet worksheet = workbook.AddWorksheet("First sheet");
// ...
return workbook;
}
do this:
public XLWorkbook CreateWorkbookWithZoom()
{
XLWorkbook workbook = new XLWorkbook(#"C:\your template file.xlsx");
IXLWorksheet worksheet = workbook.Worksheet(1);
worksheet.Name = "First sheet";
// ...
return workbook;
}
where C:\your template file.xlsx is the path of your template file.
I think you can also handle having a variable number of sheets, by copying existing (blank) worksheets instead of creating new ones. You can get creative with having different blank template worksheets to choose from, if you need to set the zoom level dynamically.
A pull request for this has been logged at https://github.com/ClosedXML/ClosedXML/pull/180