|
|
Comments and Discussions
|
|
 |

|
It helped, I tried the xls and it worked cool
|
|
|
|
|

|
Hy, I'm newbie here.
I want to ask about HttpPostedFile.
What is HttpPostedFile? How I can get the HttpPostedFile.
Can i change the HttpPostedFile with string(path and filename)?
Thanks before.
|
|
|
|

|
The second override method has the parameter "FileName" which is supposed to be the File-Path. You should be able to use that.
FYI: HttpPostedFile is the class used when someone uploads a file into a web forms FileUpload control.
|
|
|
|
|

|
Nice.
|
|
|
|

|
Thanks for sharing such a very good piece of source code. It worked just fine without much hassle.
One small correction, in ExcelImport.cs file, line 125, for-loop using already used variable (i), I had to change it to unique variable name to get it compiled. (Me using VS.Net 2010 IDE, .Net 4.0)
- Pavan Gayakwad
|
|
|
|

|
Your code works like a Gem. Thank You!!
|
|
|
|

|
awesome! I'm just looking for some articles about how to import Excel file and then I found this!
|
|
|
|

|
Some cols of several rows are not filled in the dataset. The left data is ok. the program doesn't show any errors, but the dataset not have enough data as in the excel. A strange thing is that if I open the excel file, go to cell that have data in excel(but not in DATASET), press F2 and Enter, save the excel file and run the code again, it will have data at corresponding cell in DATASET. Note that I don't format or fix anything on the excel, just F2 and Enter. It has so many cells like this and I don't know why. Is there any one meet this isssue? Hope to have your idea. I have code for 2003 .xls file and 2007 .xlsx file, both of them meet this issue, too. any suggestion is appreciated?
|
|
|
|

|
I'm sorry. You're doing the regular XLS import. it's probably all formatted as text and so it's not importing it and is just dropping the data. I'm not completely sure how to fix this. I'll look and see what i can find.
|
|
|
|

|
Sorry Colin, for not sure what you mean by "all formatted as text" but thanks so much if you can have a deep look at this issue. The code I used like your first solution(using OLE Jet engine for .xls and ACE driver for .xlsx).My excel has many cols at 2 types (text, date), but the values in a specific col are in consistent type. And note that the data it skipped is formatted as DATE (they're really a date value). All rows in that cols are formatted as DATE, but just some rows go into DATASET, others are blank/null. IMEX = 1 and IMEX = 0 are all checked but return nothing. Thanks again!!!
|
|
|
|

|
Is there any updates for this issue, Colin?I search around and see nothing :(
|
|
|
|

|
Hi,
you can try to import Excel to DataSet like this:
var excelFile = new ExcelFile();
excelFile.LoadXls(fileName);
var dataSet = new DataSet();
foreach (var worksheet in excelFile.Worksheets)
dataSet.Tables.Add(worksheet.CreateDataTable(ColumnTypeResolution.Auto));
This code uses following Excel C# library.
|
|
|
|

|
I am getting the below error when I call ImportExcelXML method
This error shows in the ReadTimout and WriteTimeout of inputFileStream
'inputFileStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
Can you please help to resolve this?
Thanks in Advance.
|
|
|
|

|
Here's what I get from googling this. Can you send me an abbreviated stack-trace of the actual exception that is thrown when you call the method?
This is normal and just means that the stream doesn't support
read/write timeouts.
Most streams don't; the base-class (System.IO.Stream) has "CanTimeout"
return false, and "ReadTimeout" / "WriteTimeout" throw an Exception.
The System.Web.HttpPostedFile functionality uses a
System.Web.HttpInputStream which doesn't alter this behavior.
|
|
|
|
|

|
Hmm... You may need to install JET (for xls documents) or ACE (for xlsx documents). I believe that windows should have JET by default, but you can google it if you need. The link for ACE is below.
ACE Download: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c06b8369-60dd-4b64-a44b-84b371ede16d&displaylang=en[^]
The connection string for XLSX documents is different:
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=1\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
|
|
|
|

|
When I attempt to call the ImportExcelXML, I receive the above exception. Does anyone have any suggestions? Please note that I am using Excel 2010 files. TIA.
|
|
|
|

|
i've seen that error but i can't really remember... huh. can you post the first couple lines of the XML file? should be something like:
<?xml version="1.0"?>
<ExampleRoot>
|
|
|
|

|
oops. actually the excel file should look like:
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook>
|
|
|
|

|
Superb and Very HelpFull article...Thanks a lot..
|
|
|
|

|
External Table not supported
|
|
|
|

|
It accepts only .xls file
|
|
|
|

|
For some reason I can't get this to compile due to ColumnType is not defined.
Any suggestions?
Thanks,
Dustin
|
|
|
|

|
sorry... here's the column type definition... and another static method i had... not sure if this will compile either. let me know... i can post the full code here
private static ColumnType getDefaultType() {
return new ColumnType(typeof(String));
}
struct ColumnType {
public Type type;
private string name;
public ColumnType(Type type) { this.type = type; this.name = type.ToString().ToLower(); }
public object ParseString(string input) {
if (String.IsNullOrEmpty(input))
return DBNull.Value;
switch (type.ToString()) {
case "system.datetime":
return DateTime.Parse(input);
case "system.decimal":
return decimal.Parse(input);
case "system.boolean":
return bool.Parse(input);
default:
return input;
}
}
}
|
|
|
|

|
here's the full code i used:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Xml;
using System.Web;
namespace ConvertToExcel {
public class ExcelImport {
public static DataSet ImportExcelXLS(HttpPostedFile file, bool hasHeaders) {
string fileName = Path.GetTempFileName();
file.SaveAs(fileName);
return ImportExcelXLS(fileName, hasHeaders);
}
private static DataSet ImportExcelXLS(string FileName, bool hasHeaders) {
string HDR = hasHeaders ? "Yes" : "No";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn)) {
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow row in dt.Rows) {
string sheet = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
}
return output;
}
struct ColumnType {
public Type type;
private string name;
public ColumnType(Type type) { this.type = type; this.name = type.ToString().ToLower(); }
public object ParseString(string input) {
if (String.IsNullOrEmpty(input))
return DBNull.Value;
switch (type.ToString()) {
case "system.datetime":
return DateTime.Parse(input);
case "system.decimal":
return decimal.Parse(input);
case "system.boolean":
return bool.Parse(input);
default:
return input;
}
}
}
public static DataSet ImportExcelXML(HttpPostedFile file, bool hasHeaders, bool autoDetectColumnType) {
return ImportExcelXML(file.InputStream, hasHeaders, autoDetectColumnType);
}
public static DataSet ImportExcelXML(Stream inputFileStream, bool hasHeaders, bool autoDetectColumnType) {
XmlDocument doc = new XmlDocument();
doc.Load(new XmlTextReader(inputFileStream));
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
nsmgr.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
nsmgr.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
DataSet ds = new DataSet();
foreach (XmlNode node in doc.DocumentElement.SelectNodes("//ss:Worksheet", nsmgr)) {
DataTable dt = new DataTable(node.Attributes["ss:Name"].Value);
ds.Tables.Add(dt);
XmlNodeList rows = node.SelectNodes("ss:Table/ss:Row", nsmgr);
if (rows.Count > 0) {
List<ColumnType> columns = new List<ColumnType>();
int startIndex = 0;
if (hasHeaders) {
foreach (XmlNode data in rows[0].SelectNodes("ss:Cell/ss:Data", nsmgr)) {
columns.Add(new ColumnType(typeof(string))); dt.Columns.Add(data.InnerText, typeof(string));
}
startIndex++;
}
if (autoDetectColumnType && rows.Count > 0) {
XmlNodeList cells = rows[startIndex].SelectNodes("ss:Cell", nsmgr);
int actualCellIndex = 0;
for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++) {
XmlNode cell = cells[cellIndex];
if (cell.Attributes["ss:Index"] != null)
actualCellIndex = int.Parse(cell.Attributes["ss:Index"].Value) - 1;
ColumnType autoDetectType = getType(cell.SelectSingleNode("ss:Data", nsmgr));
if (actualCellIndex >= dt.Columns.Count) {
dt.Columns.Add("Column" + actualCellIndex.ToString(), autoDetectType.type);
columns.Add(autoDetectType);
} else {
dt.Columns[actualCellIndex].DataType = autoDetectType.type;
columns[actualCellIndex] = autoDetectType;
}
actualCellIndex++;
}
}
for (int i = startIndex; i < rows.Count; i++) {
DataRow row = dt.NewRow();
XmlNodeList cells = rows[i].SelectNodes("ss:Cell", nsmgr);
int actualCellIndex = 0;
for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++) {
XmlNode cell = cells[cellIndex];
if (cell.Attributes["ss:Index"] != null)
actualCellIndex = int.Parse(cell.Attributes["ss:Index"].Value) - 1;
XmlNode data = cell.SelectSingleNode("ss:Data", nsmgr);
if (actualCellIndex >= dt.Columns.Count) {
for (int i = dt.Columns.Count; i < actualCellIndex; i++) {
dt.Columns.Add("Column" + actualCellIndex.ToString(), typeof(string));
columns.Add(getDefaultType());
}
ColumnType autoDetectType = getType(cell.SelectSingleNode("ss:Data", nsmgr));
dt.Columns.Add("Column" + actualCellIndex.ToString(), typeof(string));
columns.Add(autoDetectType);
}
if (data != null)
row[actualCellIndex] = data.InnerText;
actualCellIndex++;
}
dt.Rows.Add(row);
}
}
}
return ds;
}
private static ColumnType getDefaultType() {
return new ColumnType(typeof(String));
}
private static ColumnType getType(XmlNode data) {
string type = null;
if (data.Attributes["ss:Type"] == null || data.Attributes["ss:Type"].Value == null)
type = "";
else
type = data.Attributes["ss:Type"].Value;
switch (type) {
case "DateTime":
return new ColumnType(typeof(DateTime));
case "Boolean":
return new ColumnType(typeof(Boolean));
case "Number":
return new ColumnType(typeof(Decimal));
case "":
decimal test2;
if (data == null || String.IsNullOrEmpty(data.InnerText) || decimal.TryParse(data.InnerText, out test2)) {
return new ColumnType(typeof(Decimal));
} else {
return new ColumnType(typeof(String));
}
default: return new ColumnType(typeof(String));
}
}
}
}
|
|
|
|
|

|
I do not understand the downvote here.
|
|
|
|

|
I didn't downvote anything here
Sacha Barber
- Microsoft Visual C# MVP 2008-2012
- Codeproject MVP 2008-2012
Open Source ProjectsCinch SL/WPF MVVM
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
My Blog : sachabarber.net
|
|
|
|

|
Someone downvoted you. I don't know why, you posted a link to a nice article.
|
|
|
|

|
wizardzz wrote: I do not understand the downvote here.
I would suspect that it has something to do with most of Sacha's replies. He has either already done it or did it better and then points everyone to his article.
I know it irritate the crap out of me and I suspect it irritates other members as well.
"the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011) "No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011)
"It is the celestial scrotum of good luck!" - Nagy Vilmos (2011)
"But you probably have the smoothest scrotum of any grown man" - Pete O'Hanlon (2012)
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
Allows for inputting Excel tables into a DataSet.
| Type | Article |
| Licence | CPOL |
| First Posted | 8 Jan 2009 |
| Views | 109,160 |
| Downloads | 5,644 |
| Bookmarked | 88 times |
|
|