[英]ASP.NETC# error while importing data from excel
i created web application using c# to import excel file into Microsoft Dynamics CRM. 我使用c#创建了Web应用程序,将Excel文件导入Microsoft Dynamics CRM。 I used Fileupload to import the excel file. 我使用Fileupload导入excel文件。
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: 这是ImportData代码:
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. 当我尝试将Excel导入CRM时。 I got this message : "There is no row at position 0." 我收到此消息:“位置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. 实际上,在创建Web应用程序之前,我使用此代码创建了Windows应用程序,并成功导入了数据。 But when i copy this code into web application, i got that message. 但是,当我将此代码复制到Web应用程序时,我收到了该消息。
EDITED 已编辑
This is connection string inside web config: 这是Web配置内的连接字符串:
<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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.