Save XLS Using Interop Excel - c#

The Current Setup:
So, I can use the following code to save a file as an XLS:
_myWorkbook.SaveAs("FileName.xls", Excel.XlFileFormat.xlWorkbookNormal)
I can also use the following code to save a file as an XLSX (Since I use Office 2010):
_myWorkbook.SaveAs("FileName.xlsx", Excel.XlFileFormat.xlWorkbookDefault)
The Issue:
I have tried (unsuccessfully) to save the file as an XLSX using the following code:
_myWorkbook.SaveAs("FileName.xlsx", Excel.XlFileFormat.xlExcel12)
Why does this not work? Last I checked, Excel 12 was Excel 2007 (a version that supports XLSX). Am I missing something?
(For those interested, I get a This extension can not be used with the selected file type error)

Actually XlFileFormat.xlExcel12 is Excel 12.0 binary format (xlsb) , for OpenXML (i.e. xlsx) you need to use XlFileFormat.xlOpenXMLWorkbook enum value.
For a complete reference see here.

Related

How to identify an excel file(xls, xlsx, csv) which has been converted from .DLL file in c# dot net core

Basically need to identify the excel is originally created from a valid excel. I have tried using Microsoft.Interop.Excel File format.
Seems like I cannot use this without Microsoft office being installed. So need another approach for this problem.
EDIT :
Basically I want to be able to distinguish a valid excel from invalid one like an excel file which is converted from DLL. Because the file extension will say it is xls. If you try to open that file, it will open an empty workbook without any sheets. But I cannot decide an excel with no sheets is an invalid one.
If you want to idenify wheter file is a valid excel file or not, you can use 'trid file identifier'. TrID - File Identifier.
You can do it own your own also by reading magic number or file signaure bytes. Please go through this question Original file bytes from StreamReader, magic number detection.

How to convert xls file to xlsx file using C#?

I was developing an application which read data from an excel file, but when I try to open it, an exception  was thrown if the source file is saved with the xls format (File contains corrupted data error when opening Excel sheet with OpenXML). indeed when I save this file with the xlsx format it works fine. please help me to solve this problem.
Use Free Spire.XLS dll available via NuGet.
Sample:
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xls");
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);
For reliably reading XLS files you could use ExcelDataReader which is a lightweight and fast library written in C# for reading Microsoft Excel files. It supports the import of Excel files all the way back to version 2.0 of Excel (released in 1987!)
Alternatively you could use a file conversion API like Zamzar. This service has been around for 10+ years, and provides a simple REST API for file conversion - it supports XLS to XLSX conversion. You can use it in C# and it has extra features like allowing you to import and export files to and from Amazon S3, FTP servers etc.
Full disclosure: I'm the lead developer for the Zamzar API.
You cannot read xls files with OpenXML.
The solution from Microsoft is to read the xls file with Office Interop (but Interop is not recommended to be used on the server), transfer data from Interop step by step to OpenXML.
Another solution is to use an Excel library like EasyXLS and convert between these two Excel file formats:
ExcelDocument workbook = new ExcelDocument();
workbook.easy_LoadXLSFile("Excel.xls");
workbook.easy_WriteXLSXFile("Excel.xlsx");
Find more information about converting xls to xlsx.
I am not quite sure why you need to convert the file and why you don't just read the xls file, using a different technology then OpenXML, for sure.
XLS is the older Excel file format. XSLX is the newer format stored as OpenXML. XSLX is actually a zip file with the various components stored as files within it. You cannot simply rename the file to get it into the new format. To save the file in XSLX you'll have to save the file into the Excel 2010+ format.
If you're using Excel interop then it is an option on the SaveAs method.
for more info check the function: _Workbook.SaveAs Method
and the property: FileFormat:
Optional Object.
The file format to use when you save the file. For a list of valid choices,
see the FileFormat property. For an existing file, the default format is the
last file format specified; for a new file, the default is the format of the
version of Excel being used.
msdn info here:
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._workbook.saveas(v=office.11).aspx

How to inject VBA code into Excel .xlsm without using Interop?

My goal is to add macros to an excel workbook without having to enable "Trust Access to the VBA Project Object Module" in the Excel Trust Center. (Enabling access seems a security risk).
Found random pieces of puzzle on my initial fact finding search:
-I see that VBA script is stored in the zipped .xlsm file as vbaProject.bin.
-There are several free/commercial resources that can work with excel files:
Create excel without interop and template with or without row and columnspan
It would be nice to simply have a file of VBA script in the C# project that the C# code pulls from and injects into the Excel document without VBA interop. Any quick/fast/simple/straightforward way to do this or should I play around with the free/commercial resources linked to above?
Using OpenXML SDK 2.0:
Create your macro code and save it in .xlsm format, say snorehorse.xlsm.
Open snorehorse.xlsm in the OpenXML Productivity Toolkit and do a Reflect Code on the tree root.
Find the macro's binary code. It's in a string format and looks like random characters.
In your IDE, add a reference to OpenXML SDK, and programmatically create or open the excel file you want to inject the macro code into.
Copy the macro string found in step #3 into your code.
Add a new vba part to the destination.
Feed the string data into the new vba part.
Save and run and be pleased you bypassed the Trust Center.
Example code:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
private string partData = "...";
public void vbaInjector{
[code to create / open spreadsheet using OpenXML omitted]
VbaProjectPart vbaProjectPart1 = snoreSpreadsheetDoc.WorkbookPart.AddNewPart<VbaProjectPart>("rId8");
System.IO.Stream data = GetBinaryDataStream(partData);
vbaProjectPart1.FeedData(data);
data.Close();
[code to close spreadsheet and cleanup omitted]
}
private System.IO.Stream GetBinaryDataStream(string base64String)
{
return new System.IO.MemoryStream(System.Convert.FromBase64String(base64String));
}
I chose to add the OpenXML SDK dll into the project's local build so the end users won't have to install the SDK themselves.
I think this can be done on a lower level, working with the XML, without using the OpenXML SDK, but I haven't attempted to learn how to do this. If anyone can post the code, I'll accept that Answer over mine.
Also, if one had a programmatic way to convert VBA script, in an embedded resource file, into a binary string of the format excel expects, one could bypass having to copy and paste in a new string of binary data every time you wanted to change the macro code. That would be a superior answer to mine.
Thanks.
If you use EPPlus, you can now include VBA programmatically. See here:
Writing and Executing VBA Macros on Excel without using Excel.Interop

Generating Excel file from HTML

I'm aware that I can generate an HTML <table> and save it as an .xls file to read into Excel, and that works fine and all, but it only gives me one sheet.
Is there a way to generate HTML so that I can have multiple sheets in a single .xls file? I've tried to simply generate more then one <table>, but they just end up getting appended to eachother.
Short Answer: No.
Longer Answer: You cannot cause an HTML generated page to split into multiple worksheets in an Excel file. Further, the HTML you generate for even a single page could cause Excel to choke on certain machines as it does the conversion when the file is loaded. We've seen a number of low powered machines take upwards of 5 minutes to show a HTML file in excel (simple table with rows/columns, nothing fancy) depending on size.
Better Answer: Use a third party product like ClosedXML or FileHelpers to generate a proper xlsx file.
there seems to be way though I didn't try it, see http://www.c-sharpcorner.com/UploadFile/kaushikborah28/79Nick08302007171404PM/79Nick.aspx and check the Worksheets attribute
check the official documentation at http://msdn.microsoft.com/en-us/library/Aa155477%28office.10%29.aspx
After installing the Help file you can find an example of a file with 3 Worksheets in XML Reference / Excel Workbook...
You can use open source ClosedXML, а wrapper around OpenXML to conveniently generate xlsx files - i.e. Office 2007+ format Excel files.

Convert XLS to XSLX with Sharepoint and C#

I know about Word Automation Services, where I can start a ConversionJob which enable you to convert a .docx file to e.g. PDF or .doc.
I thought these services also allow the conversion of XLSX to XLS file - I was wrong. When looking at the SaveFormat Enumaration it only supports Word. Excel Automation Services don't seem to have such a conversion job?
How do I convert an XLS file to XLSX without using Excel automation (i.e. without having Excel installed on the server)?
EDIT:
In the end I used Aspose Cells for the conversion.
You might try ExcelLibrary or EPPlus those libraries allow you to write excel files without using excel COM object.
You may read cell by cell and create a new worksheet copied from the other one (copy cell by cell)
I'm note sure that you can do it (converting XLS with is a row MS Excel file without having either Excel Services or MS Excel installed [Using InterOp] to XLSX which an OpenXML format)!!
If you want a way to convert it on a PC which MS Excel install check this link out http://devville.net/blog/2011/02/05/how-to-convert-rtf-document-to-doc-using-c/
But if found a way I would be happy if u share it to use.

Categories