I generated an Excel spreadsheets in OpenXml format using EPPlus. When I try to open it using Aspose.Cells, the program returns the following error:
Aspose.Cells.CellsException: ‘Invalid cell name’
I believe the cells didn’t find the correct file format.
How can I open this file?
I am using C# and .NET Core
Thanks
I am Ahsan Iqbal from Aspose.
I have tested this issue with my own sample code but this issue is not reproduced.
static void Main(string[] args)
{
Console.WriteLine("Creating XLSX file using EPPlus");
CreateExcelFileInEpplus();
Console.WriteLine("Success in creating XLSX file using EPPlus");
ReadExcelFileUsingAsposeCells();
Console.WriteLine("Success in reading XLSX file using EPPlus");
}
static void CreateExcelFileInEpplus()
{
var newFile = new FileInfo("output.xlsx");
if (File.Exists(newFile.Name))
File.Delete(newFile.Name);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
xlPackage.Workbook.Worksheets.Add("Sheet1");
// do work here
xlPackage.Save();
}
}
static void ReadExcelFileUsingAsposeCells()
{
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook("output.xlsx");
Console.WriteLine(workbook.Worksheets[0].Name);
}
This test shows that Aspose.Cells can read the Excel spreadsheet generated by EPPlus. Your sample code and output files are required for analysis. You may please create a thread at Aspose.Cells Forum and share your code, output XLSX file, version of Aspose.Cells and .NET Core, operating system and other specific environment information if any. Our support team will assist you further in this regard.
Related
I have proper .dotm template.
When I create a new file based on a template by double clicking in explorer it creates the correct file (based on this template). Created file size after save is 16Kb (without any content).
But if I want to use .CreateFromTemplate method in my code I cannot open a newly created .docx file in MS Word.
New file size is 207Kb (just like .dotm file). MS Word display "run-time error 5398" and not open the file.
I'm using nuget package DocumentFormat.OpenXml 2.19.0, Word 365 version 16.0.14931.20648 - 32bit and code like this:
using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(templatePath))
{
doc.SaveAs(newFileName);
}
Google is silent about this error, ChatGPT says that:
The "Run-time Error 5398" error means that the file you are trying to open is corrupted or not a valid docx file. Possible reasons for this error may be the following:
The file was not saved correctly after making changes. Verify that the Save() method was called after making changes to the file.
The file was saved with the wrong extension, e.g. as DOTM instead of DOCX
The file was saved in an invalid format.
There may have been some unhandled exceptions in your code.
When I manually change the extension of a new file from docx to dotm, there is no error when opening, but the file does not open.
What am I doing wrong with CreateFromTemplate method?
I tried to reproduce the behavior you described, using the following unit tests:
public sealed class CreateFromTemplateTests
{
private readonly ITestOutputHelper _output;
public CreateFromTemplateTests(ITestOutputHelper output)
{
_output = output;
}
[Theory]
[InlineData("c:\\temp\\MacroEnabledTemplate.dotm", "c:\\temp\\MacroEnabledDocument.docm")]
[InlineData("c:\\temp\\Template.dotx", "c:\\temp\\Document.docx")]
public void CanCreateDocmFromDotm(string templatePath, string documentPath)
{
// Let's not attach the template, which is done by default. If a template is attached, the validator complains as follows:
// The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:attachedTemplate'.
using (var wordDocument = WordprocessingDocument.CreateFromTemplate(templatePath, false))
{
// Validate the document as created with CreateFromTemplate.
ValidateOpenXmlPackage(wordDocument);
// Save that document to disk so we can open it with Word, for example.
wordDocument.SaveAs(documentPath).Dispose();
}
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(documentPath, true))
{
// Validate the document that was opened from disk, just to see what Word would open.
ValidateOpenXmlPackage(wordDocument);
}
}
private void ValidateOpenXmlPackage(OpenXmlPackage openXmlPackage)
{
OpenXmlValidator validator = new(FileFormatVersions.Office2019);
List<ValidationErrorInfo> validationErrors = validator.Validate(openXmlPackage).ToList();
foreach (ValidationErrorInfo validationError in validationErrors)
{
_output.WriteLine(validationError.Description);
}
if (validationErrors.Any())
{
// Note that Word will most often be able to open the document even if there are validation errors.
throw new Exception("The validator found validation errors.");
}
}
}
In both tests, the documents are created without an issue. Looking at the Open XML markup, both documents look fine. However, while I don't get any runtime error, Word also does not open the macro-enabled document.
I am not sure why that happens. It might be related to your security settings.
Depending on whether or not you really need to use CreateFromTemplate(), you could create a .docm (rather than a .dotm) and create new macro-enabled documents by copying that .docm.
I opened an issue in the Open XML SDK project on GitHub.
Using SSJS I've successfully created a PDF using the simple HTML parser that comes with iText but the simple HTML parser doesn't respect CSS and is very limited. I downloaded the XMLWorker class from the iText site and have tried to use that instead but my knowledge of working out how to call Java packages is too limited. All the examples I can find use Java and refer to the classes directly, eg.
Document newPDF = new Document();
But in SSJS we have to use dot notation, eg.
var newPDF:com.itextpdf.text.Document = new com.itextpdf.text.Document();
This - I think - is where I stumble. My code looks like this:
function createLPO2(pReqDoc:NotesDocument) {
importPackage(com.itextpdf);
//importPackage(com.itextpdf.tool.xml.XMLWorkerHelper);
importPackage(java.io);
var con = facesContext.getExternalContext();
var response:com.ibm.xsp.webapp.XspHttpServletResponse = con.getResponse();
response.setContentType("application/pdf");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", -1);
response.setHeader("Content-Disposition","attachment; filename=\"LPO_" + pReqDoc.getItemValueString("RequisitionNo") + ".pdf\"");
var newPDF:com.itextpdf.text.Document = new com.itextpdf.text.Document();
var writer = com.itextpdf.text.pdf.PdfWriter.getInstance(newPDF,response.getOutputStream());
var xmlWorkerHelper = com.itextpdf.tool.xml.XMLWorkerHelper.getInstance();
var strHTML = getTestHTML(); //this is the HTML used in the examples on the iText site
xmlWorkerHelper.parseXHtml(writer, newPDF, new java.io.StringReader(strHTML));
newPDF.close();
writer.close();
facesContext.responseComplete();
}
If I run this script as it is I get a script error on the Domino console. If I remove the comment on the line importPackage(com.itextpdf.tool.xml.XMLWorkerHelper); it gives a completely different error. I suspect I have to import the XMLWorkerHelper package and not just the com.itextpdf package. I thought if I opened the jar file using a tool like 7-zip I could work out the path, which is how I arrived at com.itextpdf.tool.xml.XMLWorkerHelper
Is this right? If so, why does my script fail?
Rob,
seriously, don't try to do that in SSJS. iText is all Java, if you try to mangle with it in a different language it will stress you out. Create a wrapper class that has a method that takes an OutputStream and whatever data (Document, View etc) you need. Obtain the OutputStream in your SSJS and call the function. Look for the XAgent XSnippet on OpenNTF and my blog series (the last two are missing - bear with me) on PDF creation.
One word of caution: iText is GPL, so you either GPL your software too, buy a commercial iText license or look for alternatives like Apache PDFBox or Apache FOP. Ah the second caution: HTML to PDF is a Pita. You could look at a commercial tool like e.g. from Swing software (or change your approach)
I'm trying to generate a .pdf file using mPDF in a Zend Framework application, from the output of the action.
Here is the code of my action:
public function testAction()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$this->view->foo = 'bar';
$this->render();
$output = $this->getResponse()->getBody();
$layout = new Zend_Layout();
$layout->content = $output;
$layout->setLayoutPath(dirname(dirname(__FILE__)) . '/views/layouts/');
$layout->setViewSuffix('tpl');
$layout->setLayout('pdf');
$html = $layout->render();
$mpdf = new mPDF('utf-8', 'A4');
$mpdf->WriteHTML($html);
$mpdf->Output('report.pdf', 'D');
}
If the content to be displayed is long (i.e. a few paragraphs), when downloading the .pdf file, Adobe Reader throws the following error: Adobe Reader could not open 'report.pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded).
However, if I pass the same output to mpdf as a static variable, without using Zend Layout render, then the .pdf file opens without any errors. Also, Adobe Reader throws the issue if and only if the content is long (i.e. it works if there are only a couple of words).
Is there any limit I should be aware of?
there should not be space at beginning and at the end of file so check these space,
Adobe Reader is less forgiving than some othe PDF readers if the PDF file is corrupt. Open your PDF document in a text editor and check that the file starts with something like:
%PDF-1.4
%âãÃÓ
Sometimes PHP error notices are found at the top of the file.
Source : mpdf forum IanBack's answer
I am using iTextSharp dll version 4.1.2.0 for pdf merging.But it is causing some pages blank in the final merged pdf. but this issue is not present in its latest dll.
I am using .net framework 1.1 , so i can't use latest dll cause it doesn't support.
So,Please give suggestion what should i do for this.
Thanks
Yes, I have got the solutions like "if we will use latest dll then it is ok, no problem but what if we are using a dll that supports .net framework 1.1 that might be before the latest dll.
The problem in my case are some pdfs are corrupted and not able to parse correctly, that's why it is throwing an exception as "Attempt to Read Past the End of The Stream" .And i found in web that is some pdfs having some more characters after EOF Marker then it is the problem .So,we have to just remove all the characters from the file and test in the newly created pdf file. It has worked for me.
public void RemoveExtraBytes(string ofilepath,nfilepath)
{
string oldfilePath =ofilepath;
string newFilePath="nfilepath";
WebClient client = new WebClient();
byte[] buffer = client.DownloadData(filePath);
string str;
int position = 0;
str = ASCIIEncoding.ASCII.GetString(buffer);
if (str.Contains("%%EOF"))
{
position = str.LastIndexOf("%%EOF");
}
Stream stream = new System.IO.FileStream(newfilepath, FileMode.Create);
stream.Write(buffer, 0, position);
stream.Close();
}
How to convert excel data into xml file using ado.net?
You can use the Microsoft Jet OLEDB 4.0 Data Provider to read the Excel file. Information about how to establish a connection to an Excel file can be found here.
This article explains how to read an Excel file using the provider. Once you have read the data, you can compose your XML document using LINQ to XML or the System.Xml classes.
In Excel, you can save the file to XML by using the File menu and changing the saved file type to XML spreadsheet.
If you want to read an Excel XML file with ADO.Net, try the XmlReader.
Or see this step-by-step example from Microsoft.
I've not used ado.net, but I've used xquery very successfully for this. Use excel export to create an XML file, then write xquery/xpath commands to convert as you want. Excel XML export format is pretty gnarly but it does do the job. Use the Oxygen 30 day eval license to lighten the xquery debug job.
use this code :
public static DataSet exceldata(string filelocation)
{
DataSet ds = new DataSet();
OleDbCommand excelCommand = new OleDbCommand();OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
string excelConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filelocation + "; Extended Properties =Excel 8.0;";
OleDbConnection excelConn = new OleDbConnection(excelConnStr);
excelConn.Open();
DataTable dtPatterns = new DataTable();excelCommand = new OleDbCommand("SELECT UUID, `PATTERN` as PATTERN, `PLAN` as PLAN FROM [PATTERNS$]", excelConn);
excelDataAdapter.SelectCommand = excelCommand;
excelDataAdapter.Fill(dtPatterns);
dtPatterns.TableName = "Patterns";
ds.Tables.Add(dtPatterns);
return ds;
}
and then convert returned datatable to xml with DataTable.WriteXml()