在Asp.net中导入Excel需要在服务器端安装MicrosoftOffice吗?是否需要在服务器上安装Microsoftoffice才能运行将excel文件中的数据导入mssql数据库的应用程序?有什么建议或想法吗?我使用的代码publicpartialclass_Default:System.Web.UI.Page{privateStringstrConnection="DataSource=MYCBJ017550027;InitialCatalog=MySamplesDB;IntegratedSecurity=True";protectedvoidPage_Load(objectsender,EventArgse){}protectedvoidbtnSend_Click(objectsender,EventArgse){stringpath=fileuploadExcel.PostedFile.FileName;stringexcelConnectionString=@"Provider=Microsoft.ACE.OLEDB.12.0;DataSource="+path+";ExtendedProperties=Excel12.0;PersistSecurityInfo=False";OleDbConnectionexcelConnection=newOleDbConnection(excelConnectionString);OleDbCommandcmd=newOleDbCommand("从[Sheet1$]中选择[ID]、[名称]、[名称]",excelConnection);excelConnection.Open();OleDbDataReaderdReader;dReader=cmd.ExecuteReader();SqlBulkCopysqlBulk=newSqlBulkCopy(strConnection);sqlBulk.DestinationTableName="Excel_table";sqlBulk.WriteToServer(dReader);excelConnection.Close();如果您只读取xls文件,请使用内置于.netframework.4.0中的Microsoft.Jet.OLEDB如果您正在读取xlsx文件,请使用Microsoft.ACE.OLEDB.12.0。该驱动程序可从Microsoft站点免费下载。无需安装微软官方介入。使用以下连接字符串stringexcelConnectionString=@"Provider=Microsoft.ACE.OLEDB.12.0;DataSource="+path+";ExtendedProperties=Excel12.0;HDR=YES";从这里下载驱动程序请参阅此示例正如@Romil所说,您可以使用.NET框架:stringConnectionString=string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource={0};ExtendedProperties=""Excel8.0;HDR=是"";",文件名);使用(OleDbConnectionconn=newOleDbConnection(ConnectionString)){conn.Open();DataTableschemaTable=conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,newobject[]{null,null,null,"TABLE"});foreach(DataRowschemaRowinschemaTable.Rows){stringsheet=schemaRow["TABLE_NAME"].ToString();使用(OleDbCommandcmd=newOleDbCommand("SELECT*FROM["+sheet+"]",conn)){cmd.CommandType=CommandType.Text;DataTableoutputTable=newDataTable(sheet);output.Tables.Add(outputTable);新的OleDbDataAdapter(cmd).Fill(outputTable);}}conn.Close();}jet问题是,您仍然需要为其安装数据提供程序(尽管这也是免费的)或安装Office才能使其工作。如果您只需要读取excel文件,那么有很多完全托管的库可以很好地进行跟踪,而无需安装任何东西。我在这里列出了一些。我用过excelreader,效果很好。http://excelreader.codeplex.com/http://epplus.codeplex.com/Excel阅读器似乎很容易处理文档。所以这里举例说明如何使用上面是C#学习教程:在Asp.net中导入Excel需要在服务器上安装MicrosoftOffice吗?所有分享的内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——IExcelDataReaderreader=null;尝试使用(FileStreamstream=newFileStream(ofd.FileName,FileMode.Open)){stringext=System.IO.Path.GetExtension(ofd.FileName).Replace(“。”,“”).ToUpper();如果(ext=="XLS")reader=ExcelReaderFactory.CreateBinaryReader(stream);elsereader=ExcelReaderFactory.CreateOpenXmlReader(stream);reader.IsFirstRowAsColumnNames=true;使用(DataSetds=reader.AsDataSet()){foreach(DataRowdrinds.Tables[0].Rows){ImportDatatoAdd=newImportData(){Format=dr[0].ToString(),};数据库.Datastore.InsertObject(添加);}}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
