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);
Related
I need upload Excel File and then read and import its data into DataTable using C# in ASP.Net Web Application.
The imported Excel File data is then displayed in ASP.Net GridView control.
I'm using the code below but I have problem with column "AV" on the Excel File
The column "AV" contains these values
But in gridview output I have
In gridview output I don't have the numbers of Excel file source, but only "-" values
Any suggestion?
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
Master.PleaseWait();
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);
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
}
}
private void Import_To_Grid(string FilePath, string Extension, string isHDR)
{
string conStr = "";
switch (Extension)
{
case ".xls":
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
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;
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
connExcel.Open();
cmdExcel.CommandText = "SELECT * From[" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
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.
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 few columns in my excel sheet -> Job, Hours, Notes
There is a table in my database 'Tasks', where I have columns -> Task, Hours, Comment.
I have to read data from Excel file through ASP.Net page and import all data to SQL server database.
I have added FileUpload for excel file browsing and a button event to read the data.
I have seen this code:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
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);
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
}
}
private void Import_To_Grid(string FilePath, string Extension, string isHDR)
{
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();
}
But this binds with the GridView and I want to update my database. Any recommendations how that can be achieved?
Not clear. but if it is what I think it is then :
Before
//Bind Data to GridView
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
You can have an update function called which will update the database. There is not update or interaction with database here.
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();
}
}