Reading more than 255 characters from excel - c#

I am trying to read a sheet data from excel (tried both oldedb and odbc) and found out that there is 255 characters limit.
I tried using Range object as suggested in other threads
(SELECT * FROM [ref_MethodInput$A1:S362])
but still no luck. So apart from using interop is there any other way to overcome this? Registry edit is also not advisable as that would need registry edits in all client machines.

Since the issue is with the Jet Provider, why not try the Microsoft Excel Driver listed under ODBC connctions.
Source

below code work for me.
import data from excel (.xls & .xlsx) file (work for column value more than 255 character).
using Excel;
try
{
FileStream stream = File.Open(strFilePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = null;
if (extension.Trim() == ".xls")
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (extension.Trim() == ".xlsx")
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
excelReader.Close();
}
catch (Exception err)
{
mResult.Message = err.Message;
}
Download nuget packages:
1) PCLStorage (Version: 1.0.2)
2) ExcelDataReader-DevNet45 (version: 1.0.0.2)
Code reference

Related

Export information to an xlsm file, C# VS asp.net

is there a way to export information to an xlsm file? the steps I do is:
in a button I put an input to select the file, I upload the file to the server
I look for the sheet which is already specified in the code
I modify the file information according to the information to be exported
command to save the file locally.
the error is as follows:
{"The 'br' start tag on line 59 position 30 does not match the end tag of 'font'. Line 60, position 9."}
when indicating the sheet with which to work
I share my code: any suggestions?
public void ExportFile(string FileName, string UserID)
{
FileInfo fi = new FileInfo(FileName);
Master.MSGError = string.Empty;
string SheetName = "test";
using (MemoryStream file = new MemoryStream())
{
try
{
using (ExcelPackage xlPackage = new ExcelPackage(fi))
{
ExcelWorksheet worksheet;
worksheet = xlPackage.Workbook.Worksheets[SheetName]; //here is the error exception
worksheet.Cells[1, 1].Value = "TEST";
//save file
xlPackage.SaveAs(file);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(file.ToArray());
Response.Flush();
Response.End();
}
}
catch (Exception ex)
{
Master.fc.MSGError = ex.Message;
}
}
}
Currently I solved my problem I thought that the detail was in the macro, but I found the real error doing different tests, it seems that both epplus and closedxml have problems reading certain information in the excel, I ended up using closedxml and applying the solution:
OpenXml Excel: throw error in any word after mail address
I'm sorry for confusion

Parsing xlsx files with unity

I use the following code to parse an XLSX file.
private IExcelDataReader GetExcelDataReaderForFile(string filePath)
{
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
// Create the excel data reader
IExcelDataReader excelReader;
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
// Close the stream
stream.Close();
// First row are columns names
excelReader.IsFirstRowAsColumnNames = true;
return excelReader;
}
Im running this code on my android. The path is subjective to Application.persistentDataPath. The problem here is that Im getting the following strange error,
Access to the path "/tmp" is denied.
How do I sort it out? or is there any other ways to parse xlsx files in Android?
You are requesting a file/directory at the root of the drive.
You should use ./tmp (notice the .) or if you insist Application.persistentDataPath + "/tmp"

Problematic corruption of .xlsx files with NPOI - Excel cannot open the file 'file.xlsx" because the file format or file extension is not valid

When reading or modifying some user-created .xlsx files, I get the following error message:
We found a problem with some content in 'test.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.
Clicking Yes gets me another message:
Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
Example of a problem .xlsx file here (before put in NPOI).
Here's the same file, now corrupted after being read from and written back with iWorkbook.Write(filestream); here.
I have no issues creating a new .xlsx file with the following code:
string newPath = #"C:\MyPath\test.xlsx";
using (FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write))
{
IWorkbook wb = new XSSFWorkbook();
wb.CreateSheet();
ISheet s = wb.GetSheetAt(0);
IRow r = s.CreateRow(0);
r.CreateCell(0);
ICell c = r.GetCell(0);
c.SetCellValue("test");
wb.Write(fs);
fs.Close();
}
That works fine.
Even opening one of the problem child .xlsx files, setting it to an IWorkbook and writing it back to the file works:
string newPath = #"C:\MyPath\test.xlsx";
using (FileStream fs = new FileStream(newPath, FileMode.Open, FileAccess.ReadWrite))
{
IWorkbook wb = new XSSFWorkbook(fs);
wb.Write(fs);
fs.Close();
}
However, after running through code that reads from it, gets ISheets, IRows, ICells, etc.... it corrupts the .xlsx file. Even though I specifically removed anything that modifies the workbook. No Creates, Sets, Styles, etc. with NPOI.
I can't really include my code because it would just be confusing, but for the sake of completeness I'm really only using the following types and functions from NPOI during this test:
IWorkbook
XSSFWorkbook
ISheet
IRow
ICell
.GetSheetAt
.GetRow
.GetCell
.LastRowNum
So one of those causes corruption. I would like to eventually set values again and get it working like I have for .xls.
Has anyone experienced this? What are some NPOI functions that could cause corruption? Any input would be appreciated.
Edit: Using NPOI v2.2.1.
I think the problem is that you are reading from, and writing to, the same FileStream. You should be doing the read and write using separate streams.
Try it like this:
string newPath = #"C:\MyPath\test.xlsx";
// read the workbook
IWorkbook wb;
using (FileStream fs = new FileStream(newPath, FileMode.Open, FileAccess.Read))
{
wb = new XSSFWorkbook(fs);
}
// make changes
ISheet s = wb.GetSheetAt(0);
IRow r = s.GetRow(0) ?? s.CreateRow(0);
ICell c = r.GetCell(1) ?? r.CreateCell(1);
c.SetCellValue("test2");
// overwrite the workbook using a new stream
using (FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write))
{
wb.Write(fs);
}
I had the same problem. In my case the problem was not with the NPOI itself but with its dependency, SharpZipLib.
I used NPOI 2.3.0 and SharpZipLib 1.0.0. and it was given the the same error as in your case. The generated Excel was 0 bytes in size.
I downgraded the SharpZipLib back to 0.86.0 in the project where I was using the NPOI (a Service layer) and also in the MVC project(I had the package of SharpZipLib here too).
I also removed manually in web.config the assembly dependency previously created for SharpZipLib:
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
.......
<dependentAssembly>
<assemblyIdentity name="ICSharpCode.SharpZipLib" publicKeyToken="1b03e6acf1164f73" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.0.999" newVersion="1.0.0.999" />
</dependentAssembly>
</assemblyBinding>
I hope this helps someone.
I had the same error attempting to write the excel file to a memory stream and then downloading through my .net Core controller.
This code was my problem (At this point, workbook contained the NPOI excel file I created):
var fileName = $"export.xlsx";
var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
MemoryStream stream = new();
workbook.Write(stream);
byte[] output = stream.GetBuffer();
return File(output, mimeType, fileName);
The issue was this line:
byte[] output = stream.GetBuffer();
That line gave me a byte array that contained the contents of my excel file, but I did not realize that the GetBuffer returned not only the byte array representing the excel file, but also the remaining allocated memory for the byte array.
I replaced that line with this:
byte[] output = stream.ToArray();
and life was good.
When writing back to the file, be sure to use Create as FileMode method. If you use Open, the file will be corrupted because it will concatenate the new file at the end of the old one.
IWorkbook workbook;
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(file);
}
// do things to workbook...
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(file);
}

NPOI 2.2.1 generates incorrect XLSX file

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();
}

Codeplex Excel Data Reader give empty Data set for Excel 2010

I’m using Codeplex Excel Data Reader to read an excel. The problem that I face is It reads Excel 97-2003 documents without any difficulty, but when reading Excel 207-2010 documents using ExcelReaderFactory.CreateOpenXmlReader(stream), it output’s an empty data set. Did anyone faced this problem. And is any one has any solution for this?
The read method is as follows
private DataSet ReadExcel(string fileName, string extention)
{
DataSet dsData = null;
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = null;
try
{
if (extention.Equals("xls"))
{
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else
{
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
// excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
excelReader.IsFirstRowAsColumnNames = false;
dsData = excelReader.AsDataSet();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (excelReader != null)
{
excelReader.Close();
}
}
return dsData;
}
8000401a indicates it was something to do with Run As Logon Failure.
Steer clear of server-side automation of office. Or use XML to work with Excel spreadsheets on the server.
According to the support issues with the Excel Data Reader:
Design and usage are great. So far only issue I've had is with certain
XLSX file not parsing correctly (reading in wrong sheets, missind cell
values, etc). To resolve these issues, I had to rebuild Excel.dll
using latest SharpZipLib from
http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx. As
others have said, project needs an update, but is still good.
Or just use the standard micrsoft way:
Microsoft.Office.Interop.Excel.Application xlApp;
Workbook wb = null;
try
{
wb = xlApp.Workbooks.Open(filePath, false, true,5,null,"WrongPAssword");
}
foreach (object possibleSheet in wb.Sheets)
{
var aSheet = possibleSheet as Worksheet;
if (aSheet != null)
{
....

Categories

Resources