Import a Excel sheet into MS SQL database - asp.net

I have Excel 2007 and Visual Web Developer Express 2010.
I would like to import Sheet1 of an xlsx file the reader then add the data to a dataset and placing that data in a MS SQL database.
string ExcelConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
string SQLConStr = "got connection string that works";
OleDbConnection ExcelConnection = new OleDbConnection(ExcelConStr);
using (ExcelConnection)
{
string sql = string.Format("Select * FROM [{0}]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, ExcelConnection);
ExcelConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLConStr))
{
bulkCopy.DestinationTableName = "dbo.databaseName";
bulkCopy.WriteToServer(dr);
}
}
}
I need something like bulkcopy that is free and easy to use if someone may make a recommendation.

Without bulk copy it will also work.. try this it will work 100% for .csv and .xlsx both... I m using it..
string header = "No";
string sql = string.Empty;
DataTable dt = new DataTable();
string pathOnly = string.Empty;
string fileName = string.Empty;
pathOnly = Path.GetDirectoryName(path);
fileName = Path.GetFileName(path);
if (IsFirstRowHeader) { header = "Yes"; }
String cs = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=" + header + ";IMEX=1;\"";
OleDbConnection con = new OleDbConnection(cs);
if (con.State == ConnectionState.Closed) con.Open();
#region use to find sheet and fire query on sheetname
DataTable dtsheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dtsheets.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dtsheets.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
if (extension == ".csv") sql = "SELECT * FROM [" + fileName + "]";
else sql = "SELECT * FROM [" + excelSheets[0] + "]";
#endregion
OleDbCommand command = new OleDbCommand(sql, con);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
dt.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dt);
con.Close();

Related

How can I remove a CSV's header when importing it to a gridview?

I would like to ask if you have a source code for importing csv files to gridview in an ASP.NET web form.
What I want to do is remove the header on the file and display it in the grid view.
Here is a SC of my file
Read the CSV into a DataTable and then bind it into the GridView:
public void bindGrid()
{
var dt=GetDataTableFromCsv("path_to_csv_file",true);
GridView1.DataSource=dt;
GridView1.DataBind();
}
From How to read a CSV file into a .NET Datatable:
DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}

Unable to read excel sheet data on server to database

In my web based project I need to upload an excel sheet and store the data in database. The code works fine on my local machine.
However when I try to execute same code on server the data of the
excel sheet doesn't get stored in my database.
I have given relevant folder permission on server.
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
savedFileName = Guid.NewGuid().ToString() + fileExtension;
filename = Server.MapPath("~/Stockfiles/") + savedFileName;
// Place your code here to save information in database.
// Save the stream to disk
file.SaveAs(filename);
string conString = string.Empty;
switch (fileExtension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConnStringDb1"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConnStringDb1"].ConnectionString;
break;
}
conString = string.Format(conString, filename);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
OleDbCommand cmd = null;
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[3] { new DataColumn("PhoneIMEI", typeof(string)),
new DataColumn("PhonePrice",typeof(string)),new DataColumn("barcode",typeof(string))});
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
con.Open();
using (SqlTransaction sqlTransaction = con.BeginTransaction())
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con, SqlBulkCopyOptions.Default, sqlTransaction))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Stock ";
//[OPTIONAL]: Map the Excel columns with that of the database table
//sqlBulkCopy.ColumnMappings.Add("Id", "PersonId");
sqlBulkCopy.ColumnMappings.Add("PhoneIMEI", "PhoneIMEI");
sqlBulkCopy.ColumnMappings.Add("PhonePrice", "PhonePrice");
sqlBulkCopy.ColumnMappings.Add("barcode", "barcode");
try
{
sqlBulkCopy.WriteToServer(dtExcelData);
//SqlCommand getcount = new SqlCommand("select count(*) from dbo.Stock ", con);
sqlTransaction.Commit();
con.Close();
//file.SaveAs(filename);
}
Web.Config Code
<connectionStrings>
<add name="Excel03ConnStringDb1" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />
<add name="Excel07+ConnStringDb1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />
</connectionStrings>

Confused About How to insert xml value into database

I am dealing with xml files and I have found an example here.I have changed connection string and created a table named MyProducts then I have manually located my Product.xml files inside App_Data folder.When i run my program get this execption
Invalid object name 'Product'.
So in the debug mode I have noticed that myxml variable is null What am i doing wrong
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile ;
string sql = null;
int product_ID = 0;
string Product_Name = null;
double product_Price = 0;
connetionString = "Data Source=.\\sqlexpress;Initial Catalog=Northwind;Integrated Security=sspi";
connection = new SqlConnection(connetionString);
xmlFile = XmlReader.Create(Server.MapPath("~/App_Data/Product.xml"), new XmlReaderSettings());
ds.ReadXml(xmlFile);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
product_ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
Product_Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();
product_Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);
sql = "insert into Product values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
connection.Close();
Label1.Text = "ok";
}
As I've said in comments, you've just misspelled your table name - you table called MyProducts and you're trying to insert into Product
insert into MyProducts ...

How to update sql database table info with excel file using file uploaded

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}
The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

How to read data from Excel in Asp.Net

I am trying to read datas from an uploaded xls. I have used this code part:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(fileName) + ";Extended Properties=Excel 8.0");
if (connection.State == ConnectionState.Closed)
connection.Open();
string query = "select * from [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(query, connection);
DataSet ds = new DataSet();
da.Fill(ds);
But I get this error: External table is not in the expected format.
I am pretty sure I am giving the correct path. I was working and it is not. if it works then it wont fill the datatable. It gives an error that says that Sheet1$ object can not be found. Any help?
are you sure the excel version is correct? you may also want to wrap the extended properties in quotes as well. I would also recommend cleaning up your resources so you don't create memory leaks.
var path = Server.MapPath(fileName);
//where 8.0 may be a different version: 9 - 12?
var connectionString = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended ""Properties=Excel 8.0""", path);
using(var connection = new OleDbConnection(connectionString))
using(var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "select * from [Sheet1$]";
var table = new DataTable();
using(var reader = command.ExeucteReader())
{
table.Load(reader);
return table;
}
}
Have a look at this thread:
Excel "External table is not in the expected format."
Maybe you should change provider as they suggest.
One other option is to use the OpenXML SDK to read the excel file. This could get you started:
http://msdn.microsoft.com/en-us/library/ff921204.aspx
string savePath = "/Assets/UploadedFiles/";
string fileName = "Activity.xls";
savePath += fileName;
OleDbConnection conn= new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(savePath) + ";Extended Properties='Excel 12.0;HDR=YES'");
if (conn.State == ConnectionState.Closed)
conn.Open();
string query = "select * from [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Activities");
dt = ds.Tables[0];
conn.Close();
save the file in the hard disk, then add a reference to Microsoft Excel 12.0 Object Library and declare the using:
using Excel = Microsoft.Office.Interop.Excel;
then instantiate a class and load the file to read the cell values, example:
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("file.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
EDIT 1:
If you don't want to install Office in the server, you can use the excellibrary that works similar, simple as (from the author page) :
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];
// traverse cells
foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells)
{
dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
}
// traverse rows by Index
for (int rowIndex = sheet.Cells.FirstRowIndex;
rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
for (int colIndex = row.FirstColIndex;
colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
}
}

Resources