I am using OfficeOpenXml for reading the excel file in C#. But when I am trying to open and reading some sheet from it, it's throwing exception as below:
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at MS.Internal.IO.Packaging.InternalRelationshipCollection.ProcessRelationshipAttributes(XmlCompatibilityReader reader)
at MS.Internal.IO.Packaging.InternalRelationshipCollection.ParseRelationshipPart(PackagePart part)
at MS.Internal.IO.Packaging.InternalRelationshipCollection..ctor(Package package, PackagePart part)
at System.IO.Packaging.PackagePart.EnsureRelationships()
at System.IO.Packaging.PackagePart.GetRelationshipHelper(String id)
at System.IO.Packaging.PackagePart.GetRelationship(String id)
at OfficeOpenXml.ExcelWorkbook.GetExternalReferences()
at OfficeOpenXml.ExcelPackage.get_Workbook()
at ServiceHandlerUNIC.UploadTuningFile() in d:\Srusti\Projects\WECSWebConfigurator\07_SourceCode\WECSWebConfigurator\App_Code\ServiceHandlerUNIC.cs:line 56392
How can I identify this thing? Because it's working with one excel file while another excel file is throwing an error. My code is :
ExcelPackage ep = new ExcelPackage(new FileInfo(fileFUllPath));
ExcelWorksheet ws = ep.Workbook.Worksheets["Configuration"];
Related
When using Poi, even it doesn't have the sheet, it automatically creates the sheet. How to know whether it contains the sheet?
public bool Check(string Filepath, string sheetname)
{
HSSFWorkbook workbook;
using(FileStream stream = new FileStream(Filepath, FileMode.Open, FileAccess.Read){
workbook = new HSSFWorkbook(stream);
}
return workbook.contains(sheetname);
Unfortunately, NPOI / POI does not really have that feature. There is a worksheet.GetSheetAt(index) method, but it throws an exception when you try to get an index that does not exist. So if you want to try looping through possible index numbers, make sure you put a try-catch inside your loop.
I have a legacy code that imports Excel (*.xls) to our db, then move the file to specific directory after processing.
The code works fine except in one case, when the file is corrupted (even MS Excel cannot open it)! What happens in this case is that an System.AccessViolationException thrown at opening the connection!
Here is how the code looks like:
string connectionString = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""", filePath);
OleDbConnection connection = new OleDbConnection(connectionString);
try
{
connection.ConnectionString = connectionString;
connection.Open(); //<<<--- exception throws here
//file processing
}
catch (Exception e)
{
//exception handling
}
finally
{
connection.Close();
connection.Dispose();
connection = null;
GC.Collect();
}
Here is the exception details...
System.AccessViolationException was caught
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=System.Data
StackTrace:
at System.Data.Common.UnsafeNativeMethods.IDBInitializeInitialize.Invoke(IntPtr pThis)
at System.Data.OleDb.DataSourceWrapper.InitializeAndCreateSession(OleDbConnectionString constr, SessionWrapper& sessionWrapper)
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
As you can see, I am catching this exception and process it, then when the code try to move the file to another directory, I got the following exception:
System.IO.IOException occurred
Message=The process cannot access the file because it is being used by another process.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.IO.File.Move(String sourceFileName, String destFileName)
I tried to use another library, like LinqToExcel, but found it internally uses the same implementation like mine, then it is has the same problem!
I tried also to run garbage collector after the connection is closed (as you see in the above code) but faced the same problem!
Any Idea?
I tried to play around the main solution in the question with no results :(
I even checked the .NET Framework code and can see file handles somewhere in the code, but unfortunately failed to debug the code :(
I tried to decompile the .NET Framework code but failed too :(
Finally. it ends that I should use another solution, and since depending on the existence of MS Office in production machine is not an option, I went to ExcelDataReader, the open source library that reads *.xls files as binary streams, and here is how the final code looks like:
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream, true))
{
excelReader.IsFirstRowAsColumnNames = true;
var excelFileDataSet = excelReader.AsDataSet();
var sheetDataTable = excelFileDataSet.Tables["sheetName"];
//other file processing code...
}
}
And this solution works for me!
I have the same problem right now, my only solution its read the excel file using Microsoft.Office.Interop.Excel and set the MsoFileValidationMode = msoFileValidationSkip;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook;
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
**xlApp.FileValidation = MsoFileValidationMode.msoFileValidationSkip;**
xlWorkbook = xlApp.Workbooks.Open(#"C:\my file.xls");
Excel.Sheets xlWorksheet = xlWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)xlWorksheet.get_Item(3);
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A" + i.ToString(), "B" + i.ToString()); ; //UsedRange;
System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
foreach (string item in strArray)
{
MessageBox.Show(item);
}
}
... works well
Am trying to read data from an Excel file into an ADO.NET Dataset using the code below. In a windows Forms application it work, but in an asp.net application it fails.
public static DataTable ArchiveData(string fileName)
{
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
//Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
return result.Tables["Archive data"];
}
Stack Trace:
[HttpException (0x80004005): Maximum request length exceeded.]
System.Web.HttpRequest.GetEntireRawContent() +8793522
System.Web.HttpRequest.GetMultipartContent() +62
System.Web.HttpRequest.FillInFormCollection() +236
System.Web.HttpRequest.get_Form() +68
System.Web.HttpRequest.get_HasForm() +8745879
System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
System.Web.UI.Page.DeterminePostBackMode() +63
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +133
OR is there a better way of reading an Excel file from a client machine into an ADO.NET DataTable in ASP.NET
Add following tag in your web.config file and check if it works
<httpRuntime maxRequestLength="350000" enableVersionHeader="false" maxQueryStringLength="3584" executionTimeout="600"/>
I have instantiated XmlDocument and than trying to load XML file with non Latin symbols in the file pat. During loading the file I am facing with the
ArgumentNullException
with message:
"Value cannot be null. Parameter name: str"
Stack Trace is -
at System.Security.Permissions.FileIOPermission.HasIllegalCharacters(String[] str)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)
at System.Uri.ParseConfigFile(String file, IdnScopeFromConfig& idnStateConfig, IriParsingFromConfig& iriParsingConfig)
at System.Uri.GetConfig(UriIdnScope& idnScope, Boolean& iriParsing)
at System.Uri.InitializeUriConfig()
at System.Uri.InitializeUri(ParsingError err, UriKind uriKind, UriFormatException& e)
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at System.Xml.XmlResolver.ResolveUri(Uri baseUri, String relativeUri)
at System.Xml.XmlUrlResolver.ResolveUri(Uri baseUri, String relativeUri)
at System.Xml.XmlTextReaderImpl..ctor(String url, XmlNameTable nt)
at System.Xml.XmlTextReader..ctor(String url, XmlNameTable nt)
at System.Xml.XmlDocument.Load(String filename)
at ....
There is a part of my code:
var xmlData = new XmlDocument();
if (File.Exists(xmlPath))
{
xmlData.Load(xmlPath);
...
}
xmlPath contain French letters.
What is wrong?
How I can open xml file with non latin characters?
Load the file path into a uri first:
Uri xmlUri = new Uri(xmlPath);
xmlData.Load(xmlUri.AbsolutePath);
I have found solution of the problem with using other class for data loading, like this:
var d = File.ReadAllText(xmlPath);
xmlData.LoadXml(d);
But question - "what is wrong?" still open.
At the moment I am using to store the zip files with the file name like this...
backup-20111010092345.Zip
but i want to change the file name to this ..backup-2011-10-10_09:23:45.Zip
i have got this code ...
string zipName = Path.Combine(filepath, string.Format("backup-{0}.zip", DateTime.Now.ToString("yyyyMMddhhmmss")));
string backupFilePath = Path.Combine(filepath, backupName);
using (ZipFile zip = new ZipFile())
{
zip.AddFile(backupFilePath, "");
zip.Save(zipName);
}
string backupName = "backup.sql";
string filepath = #"C:\Folder\Back\";
would any one pls help on this...
many thanks In advance...
Modified Code:
string zipName = Path.Combine(filepath, string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.zip", DateTime.Now));
string backupFilePath = Path.Combine(filepath, backupName);
using (ZipFile zip = new ZipFile())
{
zip.AddFile(backupFilePath, "");
zip.Save(zipName);
}
Error :Notsupported Exception was unhandled
this is stack trace .
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.File.Move(String sourceFileName, String destFileName)
at Ionic.Zip.ZipFile.Save()
at Ionic.Zip.ZipFile.Save(String fileName)
error: The given path's format is not supported.
Sounds like you've nearly got it (in terms of building the name that you specified) - you just need to change the format string
string zipName = Path.Combine(filepath,
string.Format("backup-{0}.zip",
DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss"));
You could specify that as:
string zipName = Path.Combine(filepath,
string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.zip",
DateTime.Now));
It's up to you which you find more readable.
Note that this will use the time separator for the current culture. If you always want it to be "colon" then you should quote it. On the other hand, is colon even a valid character in Windows filenames? Consider using dash again, or something similar. For example:
string zipName = Path.Combine(filepath,
string.Format("backup-{0:yyyy-MM-dd_HH-mm-ss}.zip",
DateTime.Now));
You'll need to use something other than : as it is reserved. I suggest something like:
DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss");
As well as the build in formats, you can get the individual components of a DateTime object using its properties like myDate.Year etc. These are detailed on MSDN here:
http://msdn.microsoft.com/en-us/library/991wfdee(v=VS.90).aspx
So if you wanted some really odd formatting you could put together a composite string from each component part in whatever pattern you want.