Jena changes my owl file after adding an instance - jena

I have an owl file created with protege 4.2. when I add some Instance with Jena, Jena changes the file structure but the file extension remains the same (.owl) the file is readable in protege with some error. Anyone knows where is the problem with my code?
Because the result of the sparql query is somehow strange after the edit with Jena.
For example, Before editing with Jena
<owl:NamedIndividual rdf:about="&ontologies;thesis_ontology_1try#AM6">
<rdf:type rdf:resource="&ontologies;thesis_ontology_1try#ApplicationModel"/>
<hasID rdf:datatype="&xsd;string">20125157-d62b-45de-8809-84186c7169b5AM6</hasID>
<name rdf:datatype="&xsd;string">Gebäudemodell / Buildingmodel</name>
<hasContent rdf:resource="&ontologies;cpixml"/>
<hasLevelOfDetail rdf:resource="&ontologies;thesis_ontology_1try#4"/>
<hasDomain rdf:resource="&ontologies;thesis_ontology_1try#BIM"/>
<hasType rdf:resource="&ontologies;thesis_ontology_1try#Object"/>
<hasPhase rdf:resource="&ontologies;thesis_ontology_1try#SLCT"/>
<hasContent rdf:resource="&ontologies;thesis_ontology_1try#ifc"/>
</owl:NamedIndividual>
After Jena
<rdf:Description rdf:about="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#AM6">
<hasContent rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/cpixml"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
<hasDomain rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#BIM"/>
<hasType rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#Object"/>
<hasID rdf:datatype="http://www.w3.org/2001/XMLSchema#string">20125157-d62b-45de-8809-84186c7169b5AM6</hasID>
<hasPhase rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#SLCT"/>
<rdf:type rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#ApplicationModel"/>
<hasContent rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#ifc"/>
<name rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Gebäudemodell / Buildingmodel</name>
<hasLevelOfDetail rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#4"/>
<rdf:type rdf:nodeID="A28"/>
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
<rdf:type rdf:nodeID="A29"/>
<rdf:type rdf:nodeID="A30"/>
<rdf:type rdf:nodeID="A31"/>
<rdf:type rdf:nodeID="A32"/>
<rdf:type rdf:resource="http://www.w3.org/2000/01/rdf-schema#Resource"/>
<rdf:type rdf:nodeID="A33"/>
<rdf:type rdf:nodeID="A34"/>
<rdf:type rdf:nodeID="A12"/>
<rdf:type rdf:nodeID="A15"/>
<rdf:type rdf:nodeID="A35"/>
<rdf:type rdf:nodeID="A5"/>
<Linkedby rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#LM2"/>
<isAMof rdf:resource="http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#MMC2"/>
And This is the code
public static void main(String[] args) throws IOException {
InputStream in = FileManager.get().open("./src/thesis_ontology_1try.owl");
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF, null);
model.read(in, null);
in.close();
String NS = "http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology_1try#";
OntClass ApplicationModel = model.getOntClass(NS + "ApplicationModel");
Individual dom = model.getIndividual(NS + "RFP");
Individual pha = model.getIndividual(NS + "SLCT");
Individual lev = model.getIndividual(NS + "3");
Individual new1 = model.createIndividual(NS + "new1", ApplicationModel);
ObjectProperty domain = model.createObjectProperty(NS +"hasDomain");
ObjectProperty phase = model.createObjectProperty(NS +"hasPhase");
ObjectProperty lod = model.createObjectProperty(NS +"hasLevelOfDetail");
model.add(new1, domain, dom);
model.add(new1, phase, pha);
model.add(new1, lod, lev);
PrintStream p= new PrintStream("./src/thesis_ontology_1try.owl");
model.writeAll(p, "RDF/XML", null);
p.close();
System.out.println("Done");
}
}

model.writeAll(p, "RDF/XML", null);
try "RDF/XML-ABBREV", the pretty printer.
But either way, it's the same triples, written differently, and that's what matters.

Related

Lossing Quality after Compression using Twelvemonkeys in JAVA and highlighters are removed

I am converting a input file (PDF,TIFF) to Output (TIFF) file by using PDFBox (PDF to BufferedImage) and using twelve monkeys for converting Buffered image to Tiff file by resizing using Imagewriter with IIOImage.
File is converting but losing an quality on the image.And after changed the imagetype BufferedImage.TYPE_BYTE_GRAY to BufferedImage.TYPE_BYTE_BINARY my text highlighters on the file lost.
Below is the code used. How to convert the image without losing quality?
I am converting the image file size 1648*2338 with 200 dpi and i wanted to set photometric interpretation to min_is_white but not able to achieve my problem.
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
final int imageType = BufferedImage.TYPE_BYTE_BINARY;
// creates output image
BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight,imageType);
// scales the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// writes to output file
final List<Entry> entries =new ArrayList<Entry>();
entries.add(new TIFFEntry(TIFF.TAG_X_RESOLUTION, new Rational(200)));
entries.add(new TIFFEntry(TIFF.TAG_Y_RESOLUTION, new Rational(200)));
entries.add(new TIFFEntry(TIFF.TAG_PHOTOMETRIC_INTERPRETATION, TIFF.TYPE_SHORT, 0));
final IIOMetadata tiffImageMetadata =new TIFFImageMetadata(entries);
ImageWriter writer = ImageIO.getImageWritersByFormatName("tiff").next();
FileImageOutputStream fio = new FileImageOutputStream(new File(outputImagePath));
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
fio.setByteOrder(ByteOrder.LITTLE_ENDIAN);
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(outputImage), params);
writer.setOutput(fio);
IIOImage iioimage = new IIOImage(outputImage, null, tiffImageMetadata);
writer.write(null, iioimage, params);
fio.close();
writer.dispose();

Get all "someValuesFrom" of an object property class with Jena

I want to get all the values of "someValuesFrom" of each Object Property as a list.
I have this part of an owl file:
<owl:Class rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#ErgativeFrame">
<owl:equivalentClass>
<owl:Restriction>
<owl:onProperty rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#hasAgent"/>
<owl:someValuesFrom>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Animal"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Object"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Person"/>
</owl:unionOf>
</owl:Class>
</owl:someValuesFrom>
</owl:Restriction>
</owl:equivalentClass>
<owl:equivalentClass>
<owl:Restriction>
<owl:onProperty rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#hasMainAction"/>
<owl:someValuesFrom rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#ErgativeVerb"/>
</owl:Restriction>
</owl:equivalentClass>
<owl:equivalentClass>
<owl:Restriction>
<owl:onProperty rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#hasOptionalPatient"/>
<owl:someValuesFrom>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Animal"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Beverage"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#BodyPart"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#ClosedLocation"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Clothing"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Food"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Furniture"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#NatureElement"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#NaturePhenomenon"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#OpenLocation"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Person"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Toy"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Transport"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Vegetal"/>
</owl:unionOf>
</owl:Class>
</owl:someValuesFrom>
</owl:Restriction>
</owl:equivalentClass>
<rdfs:subClassOf rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Frame"/>
</owl:Class>
I've tried something like this:
OntClass ontClass = this.ontModel.getOntClass(NS_OWL + "ErgativeFrame");
List<OntClass> list = ontClass.listEquivalentClasses().toList();
for (OntClass equiv: list) {
if (equiv.isRestriction()) {
System.out.println("is restriction");
System.out.println(equiv.getLocalName());
}
}
The quantity of "is restriction" printed on the screen is equal to the length of properties, but getLocalName is always "null".
What do I have to do?
EDIT: I've got the name of property correctly doing some changes in the code (see below).
Now I still can't get the "someValueFrom".
OntClass ontClass = this.ontModel.getOntClass(NS_OWL + "ErgativeFrame");
List<OntClass> list = ontClass.listEquivalentClasses().toList();
for (OntClass equiv: list) {
if (equiv.isRestriction()) {
System.out.println("is restriction");
System.out.println(equiv.asRestriction().getOnProperty().getLocalName());
}
}
The reason why getLocalName is returning null is because you are using anonymous classes and properties, i.e. classes and properties without assigned URIs. Since Jena cannot find the URI, it returns null.
To illustrate, here is a subset of your ontology with named classes and properties rather than anonymous classes and properties:
<rdf:Description rdf:about="http://www.w3.org/2002/07/owl#topObjectProperty">
<rdfs:range rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#AnimalObjectPerson"/>
</rdf:Description>
<owl:Class rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Frame"/>
<owl:Class rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Object"/>
<owl:Class rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Person"/>
<owl:Class rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Animal"/>
<owl:Class rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#AnimalObjectPerson">
<owl:equivalentClass>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Animal"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Object"/>
<rdf:Description rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Person"/>
</owl:unionOf>
</owl:Class>
</owl:equivalentClass>
</owl:Class>
<owl:Class rdf:about="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#ErgativeFrame">
<owl:equivalentClass>
<owl:Restriction>
<owl:onProperty rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#hasAgent"/>
<owl:someValuesFrom rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
</owl:Restriction>
</owl:equivalentClass>
<rdfs:subClassOf rdf:resource="http://www.semanticweb.org/gumaro/ontologies/2017/11/untitled-ontology-26#Frame"/>
</owl:Class>
and here is the code for retrieving the range of the property:
OntClass ontClass = ontModel.getOntClass(NS_OWL + "ErgativeFrame");
List<OntClass> list = ontClass.listEquivalentClasses().toList();
for (OntClass equiv: list) {
if (equiv.isRestriction()) {
OntProperty ontProperty = equiv.asRestriction().getOnProperty();
OntResource range = ontProperty.getRange();
List<OntClass> rangeList = range.asClass().listEquivalentClasses().toList();
for (OntClass rangeEquiv: rangeList) {;
for (OntClass rangeUnionClass: rangeEquiv.asUnionClass().listOperands().toList()) {
System.out.println("classes in union = " + rangeUnionClass);
}
}
}
}
I hope that helps.
In the provided snippet there is ambiguous situation: the restriction ...#hasMainAction + ...#ErgativeVerb could be either Data or Object Property Existential Quantification Restriction (for more about this see owl2 guide).
There are no explicit declarations in the snippet to judge what it is exaclty.
All Restrictions are anonymous resources (class expressions) - that's why they have no uri and local name therefore.
Jena-API (the package org.apache.jena.ontology) is only for outdated OWL-1, not OWL-2.
But there is a jena-based analogue of org.apache.jena.ontology.OntModel - special for OWL-2: com.github.owlcs.ontapi.jena.model.OntModel.
Although it is not directly related to the original question, it might be more useful in this case.
Here is an example:
String fullOwlAsString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<rdf:RDF xmlns=\"http://www.semanticweb.org/owlapi/test#\"\n" +
" xml:base=\"http://www.semanticweb.org/owlapi/test\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" +
" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" +
" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
" xmlns:owl=\"http://www.w3.org/2002/07/owl#\">" +
"<owl:Ontology rdf:about=\"#\" />" + yourSnippet + "</rdf:RDF>";
InputStream in = new ByteArrayInputStream(fullOwlAsString.getBytes(StandardCharsets.UTF_8));
OntModel ont = OntManagers.createONT().loadOntologyFromOntologyDocument(in).asGraphModel();
ont.ontObjects(OntClass.ObjectSomeValuesFrom.class).map(x -> x.getValue())
.filter(x -> x.canAs(OntClass.ComponentsCE.class))
.map(x -> (OntClass.ComponentsCE<? extends OntObject>)x.as(OntClass.ComponentsCE.class))
.flatMap(x -> x.getList().members())
.filter(RDFNode::isResource).map(RDFNode::asResource).map(Resource::getLocalName)
.forEach(System.out::println);
And the output:
Animal
Beverage
BodyPart
ClosedLocation
Clothing
Food
Furniture
NatureElement
NaturePhenomenon
OpenLocation
Person
Toy
Transport
Vegetal
Animal
Object
Person

java.io.FileNotFoundException: Access denied on Image.IO.write

Im cropping 64x128 pixel Images in 4x8 and 8x16 grids and saving them in a Temp Folder to extract features from for image classification. While im doing this in a loop for multiple Images (I crop the first Image, get 8x16 subimages, extract features for each subimage, move to the next image and overwrite the existing subimages) I get an "File not found" Exception at random grid cells because access is denied for said grid cell. This only occurs when working with a big number (say 20+) of Images. How can I work around this ?
My code for the cropping part:
package imageProcess;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Crop_Raster {
BufferedImage src;
BufferedImage dst;
public Crop_Raster(BufferedImage src) {
super();
this.src = src;
}
public void cropImage_4x8() throws IOException{
int filenumber = 1;
for (int y = 0;y<4;y++){
for (int x = 0; x<8;x++){
File output = new File("Temp/"+filenumber+".jpg");
dst = src.getSubimage(16*x,16*y, 16, 16);
ImageIO.write(dst, "jpg", output);
filenumber ++;
}
}
}
public void cropImage_8x16() throws IOException{
int filenumber = 1;
for (int y = 0;y<8;y++){
for (int x = 0; x<16;x++){
File output = new File("Temp/"+filenumber+".jpg");
dst = src.getSubimage(8*x,8*y, 8, 8);
ImageIO.write(dst, "jpg", output);
filenumber ++;
}
}
}
I get the following Exception, happening while handling the second subimage of my 6th Training Image:
java.io.FileNotFoundException: Temp\2.jpg (Zugriff verweigert)
at java.io.RandomAccessFile.open0(Native Method)
at java.io.RandomAccessFile.open(Unknown Source)
at java.io.RandomAccessFile.<init>(Unknown Source)
at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at imageProcess.Crop_Raster.cropImage_8x16(Crop_Raster.java:38)
at svm.CreateVektor.createVector_8x16(CreateVektor.java:94)
at Main_Test.main(Main_Test.java:107)
The error occurs during the cropping part, the rest of my methods should work fine.
Clearing the Temp folder after each Image fixed the issue.

DBus: returning a file descriptor

I want to implement a DBus service that returns a file descriptor, but this error is raised:
** (process:3419): WARNING **: Cannot marshal type "(null)" in variant
** (process:3419): CRITICAL **: unable to append OUT arg of type GValue for create_connection: ((GValue*) 0x647730)
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff6fcd5b9 in g_type_check_value ()
from /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0
The interface I have implemented looks like this:
<node name="/org/designfu/IceService">
<interface name="org.designfu.IceService">
<annotation name="org.freedesktop.DBus.GLib.CSymbol" value="ice_service"/>
<method name="create_connection">
<!-- This is optional, and in this case is redunundant -->
<annotation name="org.freedesktop.DBus.GLib.CSymbol" value="ice_service_create_connection"/>
<arg type="b" name="controlling_mode" direction="in" />
<arg type="b" name="upnp" direction="in" />
<arg type="s" name="dbus_path" direction="out" />
<arg type="s" name="username_fragment" direction="out" />
<arg type="s" name="password" direction="out" />
<arg type="v(h)" name="send_fd" direction="out" />
<arg type="v(h)" name="recv_fd" direction="out" />
</method>
</interface>
</node>
and this is my implementation:
gboolean ice_service_create_connection(IceService *obj,
const gboolean controlling_mode,
const gboolean upnp,
char **dbus_conn_path,
char **username_fragment,
char **password,
GVariant **send_fd,
GVariant **recv_fd,
GError **error)
{
IceConnection *conn;
gboolean res;
conn = g_object_new(ICE_CONNECTION_TYPE,
"controlling-mode", controlling_mode,
"upnp", upnp,
NULL);
/* register dbus path */
char uuid_str[] = "123";
char dbus_path[512];
g_snprintf(dbus_path, 512, "/org/designfu/IceService/object/%s", uuid_str, NULL);
dbus_g_connection_register_g_object(bus, dbus_path, G_OBJECT(conn));
/* set output parameters */
*dbus_conn_path = g_strdup(dbus_path);
res = ice_connection_get_local_credentials(conn, username_fragment, password);
g_assert(res);
*send_fd = g_variant_new("(h)", conn->their_sock[SEND]);
*recv_fd = g_variant_new("(h)", conn->their_sock[RECV]);
g_assert(*send_fd);
g_assert(*recv_fd);
return TRUE;
}
If I leave out the send_fd and recv_fd output parameters, the functions works like a charm.
However, somehow I have an error in passing the file descriptors to the dbus.
The descriptors were created using
int domain = AF_LOCAL;
int type = SOCK_STREAM;
int protocol = 0;
err = socketpair(domain, type, protocol, sock);
Does anyone have a clue what's wrong here?
v(h) doesn't look like a valid DBus type signature, are you sure you don't mean (h)?

ASP.NET MVC2 and IIS 7.5 . Problems when read large data from Excel 2010

I have a problem when reading large amount of data from Excel 2010
I use the code below to read data:
public static DataTable GetExcelData(string filePath, string extension)
{
try
{
string conStr = "";
switch (extension)
{
case ".xls": //Excel 97-03
//conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
//conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR={YES}'";
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
break;
case ".xlsx": //Excel 07
//conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
break;
}
//conStr = String.Format(conStr, filePath, true);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of First Sheet
log.Debug("Excel ConnectionString = " + conStr);
connExcel.Open();
log.Debug("Open Excel connection ok");
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
log.Debug("SHEET NAME = " + SheetName);
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
return dt;
}
catch(Exception ex)
{
log.Debug("GetExcelData Error:" + ex.ToString());
return null;
}
}
My ASP.NET MVC 2.0 project works correctly when running on Visual Studio 2010 with both a small Excel file and a large Excel file.
But, when I deploy to IIS 7.5 (windows 7 pro), my website only works correctly with small Excel file.
With a large excel file, it throw the following error:
GetExcelData Error:System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format.
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
(On IIS 7.5, my website uploads large file Excel success)
How can I fix this?
It might be a web.config change that is needed to allow larger files over 4MB. You can add the following to the web.config to allow this,
<configuration>
<system.web><!-- maxRequestLength (KB) -->
<httpRuntime maxRequestLength="10000" executionTimeout="110"/>
</system.web>
</configuration>
This may help,
Maximum request length exceeded
I use the following connection string where '{0}' is the file path, for .xls files,
strConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={0};Extended Properties= ""Excel 12.0 Xml;HDR=YES;IMEX=1"""
and for .xlsx files I use,
strConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""";
It won't be the size of the files if you have set up the web.config up. I would try and save the file as an 97-2003 workbook .xls file and use the relevant connection string. If you are hosting this on a server, the server will need the Office drivers needed to process the file.
UPDATE
Set HDR to No and go through each row dismissing the header row. This will avoid a data type issue that occurs when the columns are checked for the data type.

Resources