Modify excel file with c# without deleting elements - c#

I am using the Syncfusion.XlsIO.WinForms dependency to develop with C# but when generating a file a sheet is generated that says "Created with a trial version of Syncfusion Essential XlsIO" so I think it is paid. I have been looking for a free NuGet package to modify an excel file however many dependencies remove objects like macros and textboxes on save with a function like SaveAs or Save (Macros and textboxes are part of the document). excel and I don't generate them by code, they belong to the file). I have been using a free option like ClosedXML but it deletes the elements, I have been using this code:
XLWorkbook workbook = XLWorkbook.OpenFromTemplate("C://template//from123.xlsx");
var hoja = workbook.Worksheets.Worksheet(1).Worksheet;
hoja.Cell("B11").Value = "5";
//hoja.Cell("CN").Style.Fill.SetBackgroundColor(XLColor.Black);
workbook.SaveAs(#"C://template" + "//" + "XMLCopy" + ".xlsx");
The result is as follows:
Before modifying the file
After modifying the file with c# and closedXml and saving
Do you know how I can make a modification for free and without deleting my elements?

You should open the original excel file by creating a new workbook object, modify it and then save it as a new file:
using (XLWorkbook workbook = new XLWorkbook("C://template//from123.xlsx"))
{
var hoja = workbook.Worksheets.Worksheet(1);
hoja.Cell("B11").Value = "5";
//hoja.Cell("CN").Style.Fill.SetBackgroundColor(XLColor.Black);
workbook.SaveAs(#"C://template" + "//" + "XMLCopy" + ".xlsx");
}

Related

How to solve Excel opening Error Generated by EPPlus .Net library

I am generating several excel copies from a template (its really big).
For that First I am taking the template from a file location, then based on a loop for every iteration I am creating a new ExcelPackage(newFile,Template).
After that I am taking the exact ExcelWorksheet that I have to edit.
Then after editing I am Saving as the file as newFile. The time of opening the saved file Two problem is occurring:
If there is no Excel instance is running on the PC then the saved file is opening but with no data.
If the Excel instance is running then the saved file is opening with Warning message but working. "Problem with some content with Excel. Do you want us to recover?" and "Excel was able to recover some unreadable content "
string templateExcel = #"Location\template.xlsx";
FileInfo templateFile = new FileInfo(#"Location\newFile.xlsx");
using (FileStream templateExcelStream = File.OpenRead(templateExcel))
{
using (ExcelPackage copyExcel = new ExcelPackage(templateExcelStream))
{
ExcelWorksheet presentWorkSheet = copyExcel.Workbook.Worksheets["Name"];
presentWorkSheet.Cells[4, 2].Value = Value from condition;
copyExcel.SaveAs(templateFile);
}
}
Thanks all of you for your valuable time. I got the solution.
For me the issue was in the template itself as it contained invalid references to lookup tables. I found this in Formula -> Name Manager.
I suggest that you check the template if you face this issue.

Excel Interop - Set filename before saving

Is it possible to set the excel filename before file saving?
I have following simple code:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook workbook = excel.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet sheet = workbook.Sheets[1];
sheet.Cells[1, 1] = "Hello World!";
Is it possible to predefine this name before saving?
Thanks.
There is no explicit, foolproof way to do this prior to saving, unfortunately. The closest you could come is to use a template. If you have a template called FOO.xltx, you could create your workbook like this:
Application.Workbooks.Add "X:\path\to\FOO.xltx"
The only quirk is that the name for the new documents will be appended with an incrementing number (FOO1 the first time, then FOO2,FOO3, etc.).
To create a template, just create a new document, and when you save it, select Excel Template (*.xltx) from the Save as type dropdown.
You have to use saveas to save the file with the filename you want. Then when the user clicks save it will just update the file that was previously created. Unfortunately there is no other way. Here is the code:
workbook.SaveAs(Filename: FILENAMEHERE);
Here is the MSDN doc for it: https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas.aspx

How to embed file to word docx?

I'm trying to insert a file programmatically (*.zip for example) into an existing docx file.
I looked at the docx open library but it doesn't have the function there.
Also tried using Microsoft.Office.Interop.Word. I created a word document with a table, and I'm trying to insert a file into a cell inside the table.
Word.Application wordApp = new Word.Application();
wordApp.Visible = false;
Word.Document doc = new Word.Document();
doc = wordApp.Documents.Open(Environment.CurrentDirectory + "\\test.docx");
doc.Tables[1].Rows[2].Cells[1].Range.InsertFile((Environment.CurrentDirectory + "\\tttt.zip"));
but it caused an error:
"The file appears to be corrupted"
Can anyone have experience and help with this?
After a lot of trial and error...
The function "Range.InsertFile" doesn't actually inserts a file, it reads and appends the text into the Range.
The solution was simple - Copy paste...
using System.Collections.Specialized;
...
...
//Copy the Filename to Clipboard (setFile function uses StringCollection)
StringCollection collection = new StringCollection();
collection.Add(Environment.CurrentDirectory + "\\MyFile.zip");
Clipboard.SetFileDropList(collection);
//Paste into the selected Range.
range.Paste();
*There is also function "PasteSpecial" which didn't work (Only specific data types are supported).

Open excel with EPPlus without saving to file

Rright now I'm opening excel using
System.Diagnostics.Process.Start(fileInfo);
to open my package after saving it to a file.
Is it possible to open excel without having to save the file to a location? I would like the user to decide whether or not to save the file.
If you're generating the file yourself using EPPlus (or any other libraries that generate the file directly), you'll need to save it before you can open it in Excel. I'd recommend just saving it in the temp directory, then showing it to the user and letting them choose what to do with it.
If you generate the file using Office Automation, you can display it to the user before saving it.
I think this answer will help new developer.
I think best option for viewing Excel without saving is Microsoft.Office.Interop.Excel
Open Nuget Package Console Install-Package Microsoft.Office.Interop.Excel
create Excel file here is the official documentation Excel
at the end of filling Excel file just type app.Visible = true; app is the object name
I know this is late, but I had the same issue.
I used to use Microsoft.Office.Interop.Excel to export data to an xlsx file without saving it. It would present itself nicely as Book1.xlsx to the end-user who could them save it or close it without saving as required.
I have also moved to EPPlus to improve the speed of my exports and therefore, as you have experienced, cannot present the open file to the end-user without it first being saved.
The approach I have taken, using the SaveFileDialog component is to prompt the user for a name before the EPPlus file is created. This at least allows the end-user to identify where the file should be saved, rather than using a 'hard-coded' directory.
Private Sub btnExportXlsxEPPlus_Click(sender As Object, e As EventArgs) Handles btnExportXlsxEPPlus.Click
Try
Dim filInf As FileInfo = New FileInfo(GetFileToSave())
Using excelPackage As ExcelPackage = New ExcelPackage
excelPackage.Workbook.Properties.Author = "enLIGHTen"
excelPackage.Workbook.Properties.Title = "enLIGHTen Report"
excelPackage.Workbook.Properties.Subject = "enLIGHTen export data"
excelPackage.Workbook.Properties.Created = Date.Now
Dim worksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1")
worksheet.Cells("A1").Value = "My EPPlus spreadsheet!"
worksheet.Cells(1, 2).Value = "This is cell B1!"
excelPackage.SaveAs(filInf)
End Using
Using excelPackage As ExcelPackage = New ExcelPackage(filInf)
Dim firstWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets(1)
Dim namedWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets("SomeWorksheet")
Dim anotherWorksheet As ExcelWorksheet = excelPackage.Workbook.Worksheets.FirstOrDefault(Function(x) x.Name Is "SomeWorksheet")
Dim valA1 As String = firstWorksheet.Cells("A1").Value.ToString
Dim valB1 As String = firstWorksheet.Cells(1, 2).Value.ToString
excelPackage.Save()
End Using
Dim proc As Process
Try
proc = New Process()
Process.Start(filInf.FullName)
Catch ex As Exception
MsgBox("File cannot be opened", MsgBoxStyle.Information, "Cannot open file")
End Try
Catch
End Try
End Sub
Public Function GetFileToSave()
Dim strFilename As String = ""
SaveFileDialog1.Filter = "Excel Workbook (*.xlsx)|*.xlsx"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFilename = SaveFileDialog1.FileName
Return strFilename
End If
End Function

creating an excel file and automatically expanding column widths

I have a regular html table:
<table>
<tr>hello</tr>
<tr>world</tr>
</table>
and I am creating an XLS file out of it:
string randomname = #"C:\attachmentsfolder\" + System.IO.Path.GetRandomFileName() + ".xls";
System.IO.File.WriteAllText( randomname, message);
When I open the XLS file generated, I need to MANUALLY expand the columns in order to see long data.
My question is: How can I generate this XLS file such that the columns are already sized properly?
You could do that easily with EPPlus (Open Source .NET Excel 2007+ library), and you will have a valid excel file, here is the example code :
public static void FitAndSaveToExcel(FileInfo excelFile, string sheetName)
{
ExcelPackage pack = new ExcelPackage();
ExcelWorksheet ws = pack.Workbook.Worksheets.Add(sheetName);
ws.Cells[1, 1].Value = "Some Long text that needs fitting!";
ws.Cells[1, 2].Value = "Short one";
ws.Column(1).AutoFit();
pack.SaveAs(excelFile);
}
In Excel VBA, you can achieve the effect you seek with Rng.Columns.AutoFit. I believe the C# equivalent is Rng.Columns.AutoFit();.
However, I agree with Diodeus, you will have to fix your html first.
You also could use a third-party tool like e.g. Aspose.Cells to create the Excel file.
I've used this in a lot of projects successfully. It provides the auto-fit function that you require.

Categories