我们是否需要在服务器中安装Microsoft Office以便在Asp.net中导入Excel?

我们是否需要在服务器中安装Microsoft office来运行应用程序以将数据从excel文件导入到mssql数据库?

有什么建议或想法吗?

我用的代码

public partial class _Default : System.Web.UI.Page { private String strConnection = "Data Source=MYCBJ017550027;Initial Catalog=MySamplesDB;Integrated Security=True"; protected void Page_Load(object sender, EventArgs e) { } protected void btnSend_Click(object sender, EventArgs e) { string path = fileuploadExcel.PostedFile.FileName; string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False"; OleDbConnection excelConnection =new OleDbConnection(excelConnectionString); OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]",excelConnection); excelConnection.Open(); OleDbDataReader dReader; dReader = cmd.ExecuteReader(); SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection); sqlBulk.DestinationTableName = "Excel_table"; sqlBulk.WriteToServer(dReader); excelConnection.Close(); } } 

如果您只读取xls文件,则使用内置于.net框架的Microsoft.Jet.OLEDB.4.0

如果您正在阅读xlsx文件,请使用Microsoft.ACE.OLEDB.12.0 。 可以从Microsoft站点免费下载此驱动程序。 您无需安装Microsoft官员进行干预。

使用以下连接字符串

  string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + path + ";Extended Properties=Excel 12.0;HDR=YES"; 

从这里下载驱动程序

请参阅此示例

正如@Romil所说,你可以使用.NET框架:

 string ConnectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=""Excel 8.0;HDR=Yes"";", fileName); using (OleDbConnection conn = new OleDbConnection(ConnectionString)) { conn.Open(); DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); foreach (DataRow schemaRow in schemaTable.Rows) { string sheet = schemaRow["TABLE_NAME"].ToString(); using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn)) { cmd.CommandType = CommandType.Text; DataTable outputTable = new DataTable(sheet); output.Tables.Add(outputTable); new OleDbDataAdapter(cmd).Fill(outputTable); } } conn.Close(); } 

jet的问题是,你仍然需要为它安装数据提供程序(虽然这也是免费的)或安装办公室以使其工作。 如果您只需要阅读一个excel文件,那里有很多完全管理的库,可以很好地完成跟踪而无需安装任何东西。

我在这里列出了一些。 我已经使用了excelreader,效果很好。

http://excelreader.codeplex.com/
http://epplus.codeplex.com/

Excel阅读器似乎在文档方面很轻松。 所以这是一个如何使用它的例子

 IExcelDataReader reader = null; try { using (FileStream stream = new FileStream(ofd.FileName, FileMode.Open)) { string ext = System.IO.Path.GetExtension(ofd.FileName).Replace(".", "").ToUpper(); if (ext == "XLS") reader = ExcelReaderFactory.CreateBinaryReader(stream); else reader = ExcelReaderFactory.CreateOpenXmlReader(stream); reader.IsFirstRowAsColumnNames = true; using (DataSet ds = reader.AsDataSet()) { foreach (DataRow dr in ds.Tables[0].Rows) { ImportData toAdd = new ImportData() { Format = dr[0].ToString(), }; Database.Datastore.InsertObject(toAdd); } } } }