I'm reading data from Excel through OledbConnection. Here data are reading on my local perfectly but it is missing to read if 600 more than on server.
for exmample:
I have in excel 1603 rows. It just read 636 row on server.
My connection string:
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />
My controller codes:
string filePath = string.Empty;
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
string conString = string.Empty;
switch (extension)
{
case ".xls": //For Excel 97-03.
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //For Excel 07 and above.
conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
try
{
DataTable dt = new DataTable();
conString = string.Format(conString, filePath);
using (OleDbConnection connExcel = new OleDbConnection(conString))
{
using (OleDbCommand cmdExcel = new OleDbCommand())
{
using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
{
cmdExcel.Connection = connExcel;
//Get the name of First Sheet.
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet.
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(dt);
connExcel.Close();
}
}
}
}
Thanks for helping.
Related
I made a program to open Excel file.
There are exist data page and blank page.
Can I add only the pages where the data exists in the combo box?
Can I use ButtonEvent to view only pages that contain data?
string filePath = openFileDialog1.FileName;//파일 경로 가져오기
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
//string connectionString = string.Empty;
string sheetName = string.Empty;
using (OleDbConnection con = new OleDbConnection(ConnectStr()))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
public string ConnectStr()
{
string filePath = openFileDialog1.FileName;
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
string connectionString = string.Empty;
string sheetName = string.Empty;
switch (fileExtension)
{
case ".xls": //Excel 97-03버전
connectionString = string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07이상 버전
connectionString = string.Format(Excel16ConString, filePath);
break;
}
return connectionString;
}
I don't really get what is this. But I beg you need to show only specific sheet from spreadsheet correct me if i'm wrong.
There is a SQL commend that we can query from the specific sheet.
try
{
this.txtImportFilePath.Text = opd.FileName;
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + this.txtImportFilePath.Text + ";Extended Properties=Excel 8.0;");
StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("Select * From [Sheet1$]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
DataView dvEmp = new DataView(dsXLS.Tables[0]);
trnxlistDataview.DataSource = dvEmp;
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
I have this piece of code, and I am trying to import data from an Excel File to SQL server using ASP.net but it is throwing an error and I cant Figure Out Why?
when compiled it says The Connection String property has not been initialized. any help is appreciated thanks ?
protected void LoadFile(object sender, EventArgs e)
{
{
//Upload and save the file
string excelPath = Path.GetFileName(FileUpload1.PostedFile.FileName);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
break;
case ".xlsx": //Excel 07 or higher
conString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["toll"].ToString();
DataTable dtExcelData = new DataTable();
dtExcelData.Columns.AddRange(new DataColumn[4] {
new DataColumn("Tag", typeof(string)),
new DataColumn("Exit",typeof(string)),
new DataColumn("Location",typeof(string)),
new DataColumn("Amount",typeof(decimal)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
using (SqlConnection con = new SqlConnection(ConString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "MY Table";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Amount", "Amount");
sqlBulkCopy.ColumnMappings.Add("Tag", "Tag");
sqlBulkCopy.ColumnMappings.Add("Exit", "Exit");
sqlBulkCopy.ColumnMappings.Add("Exit", "Exit");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
I know this might be a repeated question but I couldn't find it anywhere.
I am importing data from excel to gridview but how do I save the gridview data into database and the column from the gridview are auto generated.
The data is already reflected in the gridview how do i save it in the database?
It would be better if anyone can teach me how to insert directly from excel to database without using gridview as the medium.(tried using this but kept telling me that the excel sheet does not exist).
code to bind grid view:
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
.ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
.ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, isHDR);
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
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
//Bind Data to GridView
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
Yes I am using code from aspsnippets.
I recently done this, but i only did it for fileType Microsoft Office Excel Worksheet (.xlsx) . At first you have to copy the excel file to your Application directory, Then you save the data to DataTable and finally bind it to Gridview.
Use these namespaces
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
Here is the method
private void Import_To_GridTest(string FilePath)
{
DataTable dt =new DataTable();
try
{
string sSheetName = null;
string sConnection = null;
DataTable dtTablesList = default(DataTable);
OleDbDataAdapter oda = new OleDbDataAdapter();
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=YES;IMEX=1\"";
sConnection = String.Format(sConnection, FilePath);
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();
dtTablesList = oleExcelConnection.GetSchema("Tables");
if (dtTablesList.Rows.Count > 0)
{
sSheetName = dtTablesList.Rows[0]["TABLE_NAME"].ToString();
}
dtTablesList.Clear();
dtTablesList.Dispose();
if (!string.IsNullOrEmpty(sSheetName))
{
var oleExcelCommand = oleExcelConnection.CreateCommand();
oleExcelCommand.CommandText = "Select * From [" + sSheetName + "]";
oleExcelCommand.CommandType = CommandType.Text;
oda.SelectCommand = oleExcelCommand;
oda.Fill(dt);
oleExcelConnection.Close();
}
oleExcelConnection.Close();
gridview1.DataSource = dt;
gridview1.DataBind();
}
catch (Exception e)
{
lblMsg.Text = "Unspecified Error Occured..!! <br>" + e.Message;
divMsg.Attributes["class"] = "alert alert-danger";
mainDiv.Visible = true;
File.Delete(FilePath);
}
}
Finally the Submit button Click event
protected void btnsubmit_OnClick(object sender, EventArgs e)
{
if (fileUpload1.HasFiles)
{
string FileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
string FolderPath = "Excels/"; // your path
string FilePath = Server.MapPath(FolderPath + DateTime.Now.ToString("ddmmyyhhmmss") + FileName);
// copy and save the the excel
fileUpload1.SaveAs(FilePath);
Import_To_GridTest(FilePath);
}
}
Update : For saving data to database Use SqlBulkCopy Class
private void SqlbulkCopy(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string consString = ConfigurationManager.ConnectionStrings["Bulkcopy"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.leads";
//[OPTIONAL]: Map the DataTable columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Currunt_Company", "CuCompany");
sqlBulkCopy.ColumnMappings.Add("Currunt_Product", "CuProduct");
sqlBulkCopy.ColumnMappings.Add("Quantity", "Quantity");
sqlBulkCopy.ColumnMappings.Add("Unit_Price", "UnitPrice");
sqlBulkCopy.ColumnMappings.Add("Total_Price", "TotalPrice");
sqlBulkCopy.ColumnMappings.Add("Contect_Person", "ContectPerson");
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
}
i created web application using c# to import excel file into Microsoft Dynamics CRM. I used Fileupload to import the excel file.
Here is the code snippet:
Import Button:
if (FileUpload1.PostedFile != null)
{
string FilePath = Path.GetFileName(this.FileUpload1.FileName);
string FileName = Server.MapPath(Path.GetFileName(FilePath));
string Extension = Path.GetExtension(this.FileUpload1.FileName);
DataTable dt = ImportData(FileName, Extension);
And this is the ImportData code:
private DataTable ImportData(string Filepath, string Extension)
{
string connString = "";
DataTable dt = new DataTable();
switch (Extension)
{
case ".xls":
connString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
connString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
connString = string.Format(connString, Filepath, 1);
try
{
OleDbConnection excelConn = new OleDbConnection(connString);
OleDbCommand excelCmd = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
excelCmd.Connection = excelConn;
excelConn.Open();
DataTable dtexcelschema;
dtexcelschema = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtexcelschema.Rows[0]["TABLE_NAME"].ToString(); **The Error Come from this line**
excelConn.Close();
excelConn.Open();
excelCmd.CommandText = "Select * from [" + SheetName + "]";
oda.SelectCommand = excelCmd;
oda.Fill(dt);
excelConn.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
return dt;
}
When i tried to import excel to CRM. I got this message : "There is no row at position 0."
I dont know what happen here. Actually before i create web application, i created windows application using this code, and succes to import data. But when i copy this code into web application, i got that message.
EDITED
This is connection string inside web config:
<add name ="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
<add name ="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR={1}'"/>
Use This:
string Filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string Folderpath = ConfigurationManager.AppSettings["FolderPath"];
string Filepath = Server.MapPath(Folderpath + Filename);
FileUpload1.SaveAs(Filepath);
DataTable dt = ImportData(Filepath, Extension);
I'm having a excel file in a folder. but i dont know to fetch that file from the folder.
but I'm checking whether the file exists.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
string filePath = Server.MapPath("~/Upload/Sample.xlsx");
bool fileexists = File.Exists(filePath); //Here fileexists = true
}
I need to save that excel file in sql database.
I need to save the fileName(varchar(256)),Data(varbinary(max)),Path(varchar(256)) of that excel file into sql database.
please help me out
Try this to get and read an xlsx file .
if (Directory.Exists(Server.MapPath("path")))
{
string filename = Path.GetFileName("path");// to get filename
string conStr = string.Empty;
string extension = Path.GetExtension(filename);// get extension
if (extension == ".xls" || extension == ".xlsx")
{
switch (extension)
{
case ".xls": //Excel 1997-2003
conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + mappingPath + "';" + "Extended Properties=Excel 8.0;";
break;
case ".xlsx": //Excel 2007
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='" + mappingPath + "';" + "Extended Properties=Excel 8.0;";
break;
default:
break;
}
OleDbConnection connExcel = new OleDbConnection(conStr.ToString());
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
ViewState["SheetName"] = SheetName;
//Selecting Values from the first sheet
//Sheet name must be as Sheet1
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * From [" + SheetName + "]", conStr.ToString()); // to fetch data from excel
da.Fill(dtExcel);
}
This is much simpler than you think, it should be something like:
if (File.Exists(filePath)) {
byte[] data = File.ReadAllBytes(filePath);
string fileName = Path.GetFileName(filePath);
const string query = "INSERT INTO Files (FileName, Data, Path) VALUES (#FileName, #Data, #Path)";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection)) {
command.Parameters.AddWithValue("#FileName", fileName);
command.Parameters.AddWithValue("#Data", data);
command.Parameters.AddWithValue("#Path", filePath);
connection.Open();
command.ExecuteNonQuery();
}
}