I am working with ClosedXML utility for excel operations. It only supports files created on office versions 2007 on-words. I have an xls file and required to convert to xlms(macro enabled). Simple copy as shown below is not working.
string oldFile = #"C:\Files\xls.xls";
string newFile = #"C:\Files\xlsnew.xlsm";
File.Copy(xls_file,xlsm_file);
And I have used below code also
byte[] byteArray = File.ReadAllBytes(oldFile);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
{
// Change from template type to workbook type
spreadsheetDoc.ChangeDocumentType(SpreadsheetDocumentType.MacroEnabledWorkbook);
}
File.WriteAllBytes(newFile, stream.ToArray());
}
Please provide a helpful solution.
Thanks in advance.
Related
I used this code to write to an exciting excel file. After writing the file, when I open the file manually it is corrupted. I am using NPOI binary 2.3.0.0 Please tell how to avoid excel getting corrupted.
[Authorize]
public void ExportUsers()
{
var path = Server.MapPath(#"~\Content\ExportTemplates\") + "sample.xlsx";
FileStream sw = new FileStream(path, FileMode.Open, FileAccess.Read);
IWorkbook workbook = WorkbookFactory.Create(sw);
ISheet sheet = workbook.GetSheetAt(0);
IRow row = sheet.GetRow(12);
ICell cell = row.CreateCell(row.LastCellNum);
cell.SetCellValue("test");
workbook.CreateSheet("Ripon");
sw.Close();
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
string saveAsFileName = string.Format("Export-{0:d}.xls", DateTime.Now).Replace("/", "-");
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.BinaryWrite(exportData.GetBuffer());
System.Web.HttpContext.Current.Response.End();
}
}
New file is created but corrupted. I've seen people say this is fixed in version 2.0.6, but still not working for me
There are several problems going on here.
First, you are starting with an .xlsx file but then changing the download file extension to .xls. .xls and .xlsx are not the same file format; the former is a binary format, while the latter is a zipped XML format. If you save the file with the wrong extension, then Excel will report the file as corrupted when it is opened.
Second, you are using the wrong method to get the data from the MemoryStream. GetBuffer will return the entire allocated internal buffer array, which will include any unused bytes that are beyond the end of the data if the buffer is not completely full. The extra null bytes will cause the downloaded file to be corrupted. If you want to get just the data in the buffer then you should use ToArray instead.
Third, it looks like you are using the ASP.NET MVC framework (based on the presence of the [Authorize] attribute on your method) but you are directly manipulating the current response instead of using the controller's built-in File method for returning a downloadable file. I would recommend using the built-in methods where possible, as it will make your code much cleaner.
Here is the corrected code:
[Authorize]
public ActionResult ExportUsers()
{
var path = Server.MapPath(#"~\Content\ExportTemplates\") + "sample.xlsx";
FileStream sw = new FileStream(path, FileMode.Open, FileAccess.Read);
IWorkbook workbook = WorkbookFactory.Create(sw);
ISheet sheet = workbook.GetSheetAt(0);
IRow row = sheet.GetRow(12);
ICell cell = row.CreateCell(row.LastCellNum);
cell.SetCellValue("test");
workbook.CreateSheet("Ripon");
sw.Close();
var exportData = new MemoryStream();
workbook.Write(exportData);
exportData.Seek(0, SeekOrigin.Begin); // reset stream to beginning so it can be read
string saveAsFileName = string.Format("Export-{0:d}.xlsx", DateTime.Now).Replace("/", "-");
return File(exportData, "application/vnd.ms-excel", saveAsFileName);
}
I have NPOI 2.2.1 and I realized that when generating XLSX file and opening with Excel 2013, a message box telling that a problem was encountered but Excel could try to recover from it. When I click "Yes", the sheet is finally shown.
This is the code:
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet(this.Title);
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
return exportData.GetBuffer();
}
As you see, I am only creating the workbook, adding a sheet and then returning the bytes array. That array is stored in file using this code:
string targetFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), String.Concat(btnExportar.Tag, "_", DateTime.Now.ToString("yyyyMMddHHmmss"), ".xlsx"));
System.IO.File.WriteAllBytes(targetFile, xls.GetExcelData());
With XLS files there is no problem.
Regards
Jaime
The problem is not with NPOI, but with your use of GetBuffer(). That is not the method you want to use for this purpose, as GetBuffer() returns the raw buffer underlying the memory stream (usually oversized), without cutting it off at the current position of the stream. This will leave uninitialized data at the end, causing the error message in Excel.
The get all the bytes from a MemoryStream, use ToArray():
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
// return exportData.GetBuffer();
return exportData.ToArray();
}
I am using iTextSharp in my MVC application to create a .pdf file, but is there a way to convert it to a .doc file?
public ActionResult Download(int? Id)
{
string FileName = "Test";
var FilePath = Path.Combine(Path.GetTempPath(), "Temp.pdf");
Document UserPDF = new Document();
PdfWriter.GetInstance(UserPDF, new FileStream(FilePath, FileMode.Create));
CreateCv(UserPDF); // This is where the PDF is created
var fs = new FileStream(FilePath, FileMode.Open);
var Bytes = new byte[fs.Length];
fs.Read(Bytes, 0, (int)fs.Length);
fs.Close();
return File(Bytes, "application/pdf", FileName + ".pdf");
}
To put it simply, no. There is no way to convert it to a DOC file using iTextSharp. It only supports the reading and generating of PDF files.
Converting PDF to DOC is possible by using some other third party libraries but there is no solid way of doing it (and preserving formatting / whitespace) at the moment. If you search the web, people suggest creating an image from the PDF and then appending the image to the end of a blank DOC file (which is a major hack).
I'm using the EPPLUS library to read data from Excel to create another file. Unfortunately it does not support the .XLSM extension file. Is there a nice way to convert .XLSM files to .XLSX file for the purpose of reading the file with EPPLUS?
(using EPPLUS for reading would be nice because all my code is already written using it :) )
In order to do this you will need to use the Open XML SDK 2.0. Below is a snippet of code that worked for me when I tried it:
byte[] byteArray = File.ReadAllBytes("C:\\temp\\test.xlsm");
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
{
// Change from template type to workbook type
spreadsheetDoc.ChangeDocumentType(SpreadsheetDocumentType.Workbook);
}
File.WriteAllBytes("C:\\temp\\test.xlsx", stream.ToArray());
}
What this code does is it takes your macro enabled workbook file and opens it into a SpreadsheetDocument object. The type of this object is MacroEnabledWorkbook, but since you want it as a Workbook you call the ChangeDocumentType method to change it from a MacroEnabledWorkbook to a Workbook. This will work since the underlying XML is the same between a .xlsm and a .xlsx file.
Using the Open XML SDK, like in amurra's answer, but
in addition to changing doc type, VbaDataPart and VbaProjectPart should be removed, otherwise Excel will show error a file is corrupted.
using (var inputStream = File.OpenRead("C:\\temp\\test.xlsm"))
using (var outStream = new MemoryStream()) {
inputStream.CopyTo(outStream);
using (var doc = SpreadsheetDocument.Open(outStream, true)) {
doc.DeletePartsRecursivelyOfType<VbaDataPart>();
doc.DeletePartsRecursivelyOfType<VbaProjectPart>();
doc.ChangeDocumentType(DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook);
}
File.WriteAllBytes("C:\\temp\\test.xlsx", outStream.ToArray());
}
package xlsbtoxlsx;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Pattern;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbookType;
public class XlsbToXlsxConvertor {
public static void main(String[] args) throws Exception {
String inputpath="C:\\Excel Data Files\\XLSB\\CSD_TDR_20200823";
String outputpath="C:\\Excel Data Files\\XLSB\\output";
new XlsbToXlsxConvertor().xlsmToxlsxFileConvertor(inputpath, outputpath);
}
public void xlsmToxlsxFileConvertor(String inputpath, String outputpath) throws Exception {
XSSFWorkbook workbook;
FileOutputStream out;
System.out.println("inputpath " + inputpath);
File directoryPath = new File(inputpath);
// List of all files and directories
String contents[] = directoryPath.list();
System.out.println("List of files and directories in the specified directory:");
for (int i = 0; i < contents.length; i++) {
System.out.println(contents[i]);
// create workbook from XLSM template
workbook = (XSSFWorkbook) WorkbookFactory
.create(new FileInputStream(inputpath + File.separator + contents[i]));
// save copy as XLSX ----------------START
OPCPackage opcpackage = workbook.getPackage();
// get and remove the vbaProject.bin part from the package
PackagePart vbapart = opcpackage.getPartsByName(Pattern.compile("/xl/vbaProject.bin")).get(0);
opcpackage.removePart(vbapart);
// get and remove the relationship to the removed vbaProject.bin part from the
// package
PackagePart wbpart = workbook.getPackagePart();
PackageRelationshipCollection wbrelcollection = wbpart
.getRelationshipsByType("http://schemas.microsoft.com/office/2006/relationships/vbaProject");
for (PackageRelationship relship : wbrelcollection) {
wbpart.removeRelationship(relship.getId());
}
// set content type to XLSX
workbook.setWorkbookType(XSSFWorkbookType.XLSX);
// write out the XLSX
out = new FileOutputStream(outputpath + File.separator + contents[i].replace(".xlsm", "") + ".xlsx");
workbook.write(out);
out.close();
System.out.println("done");
workbook.close();
}
}
}
I'm using CarlosAg ExcelXmlWriter library which generates XML Excel spreadsheets 2003 (*.xml)
I need to find coomercial or free tool just that converts this generated xml spreadsheet into
PDF. I tried SautinSoft library but it didn't work with my desired extension (xml) it only works with xlsx or xls extesnions
thanks guys in advance
Try Aspose.
http://www.aspose.com/categories/.net-components/aspose.cells-for-.net/default.aspx
You might also need the PDF component, not sure how they do it now.
Can you simply use some pdf printer to do it?
Try to use a free solution (EpPlus): https://github.com/EPPlusSoftware/EPPlus
Or SpreadSheet https://spreadsheetlight.com/
An another way:
static void ConvertFromStream()
{
// The conversion process will be done completely in memory.
string inpFile = #"..\..\..\example.xml";
string outFile = #"ResultStream.pdf";
byte[] inpData = File.ReadAllBytes(inpFile);
byte[] outData = null;
using (MemoryStream msInp = new MemoryStream(inpData))
{
// Load a document.
DocumentCore dc = DocumentCore.Load(msInp, new XMLLoadOptions());
// Save the document to PDF format.
using (MemoryStream outMs = new MemoryStream())
{
dc.Save(outMs, new PdfSaveOptions() );
outData = outMs.ToArray();
}
// Show the result for demonstration purposes.
if (outData != null)
{
File.WriteAllBytes(outFile, outData);
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
}
}