如何使用C#将Excel csv或xls文件的行从远程位置读取到ASP.NET应用程序中?

这是我的情况。 我正在devise一个程序,它从远程networking驱动器中获取Excel文件(可能是csv,xls或xlsx格式),处理数据,然后输出并存储该过程的结果。 该程序提供了从远程networking驱动器文件夹获取的文件名列表框,使用此处接受的答案中详述的方法。 一旦用户从列表框中select了一个文件名,我希望程序find这个文件并从中获取信息来做数据处理。 我曾尝试使用此方法在线程安全上下文中从Excel文件中读取数据,但该方法只是失败,没有提供任何types的错误。 似乎没有终止。 我是否以错误的方式去做这件事?

编辑 – (最后的注意事项:我已经拿出了OleDbDataAdapter并用EPPlus处理代替它。)

我能够清除代码中的敏感数据,所以这里是:

protected void GetFile(object principalObj) { if (principalObj == null) { throw new ArgumentNullException("principalObj"); } IPrincipal principal = (IPrincipal)principalObj; Thread.CurrentPrincipal = principal; WindowsIdentity identity = principal.Identity as WindowsIdentity; WindowsImpersonationContext impersonationContext = null; if (identity != null) { impersonationContext = identity.Impersonate(); } try { string fileName = string.Format("{0}\\" + Files.SelectedValue, @"RemoteDirectoryHere"); string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.14.0; data source={0}; Extended Properties=Excel 14.0;", fileName); OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Sheet1", connectionString); DataSet ds = new DataSet(); adapter.Fill(ds, "Sheet1"); dataTable = ds.Tables["Sheet1"]; } finally { if (impersonationContext != null) { impersonationContext.Undo(); } } } 

其他编辑

现在xlsx文件已被添加到组合中。

第三方

在这种情况下,第三方解决scheme是不可接受的(除非他们允许无限制的商业用途)。

尝试 – (最后说明:最终我不得不放弃OleDb连接。)

我已经尝试了所提供的所有不同的连接string,而且我一次只用一种文件types来尝试它们。 没有任何连接string与任何文件types一起工作。

权限

用户可以访问文件及其目录。

您的连接string可能是这里的问题。 据我所知,没有一个可以读取所有的xls,csv和xlsx。 我想你正在使用XLSX连接string。

当我读取xls时,我使用下面的连接string:

@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"

话虽如此,我推荐使用第三方文件阅读器/parsing器来读取XLS和CSV,因为从我的经验来看,OleDbDataAdapter依赖于正在读取的数据types(以及它们在每列中是如何混合的)。

对于XLS,请尝试NPOI https://code.google.com/p/npoi/

对于CSV,请尝试http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader

对于XLSX,请尝试EPPlus http://epplus.codeplex.com/

上面的图书馆已经取得了巨大的成功。

为此使用OleDb接口真的很重要吗? 我一直用Microsoft.Office.Excel.Interop做到这一点,

 using System; using Microsoft.Office.Interop.Excel; namespace StackOverflowExample { class Program { static void Main(string[] args) { var app = new Application(); var wkbk = app.Workbooks.Open(@"c:\data\foo.xls") as Workbook; var wksht = wkbk.Sheets[1] as Worksheet; // not zero-based! for (int row = 1; row <= 100; row++) // not zero-based! { Console.WriteLine("This is row #" + row.ToString()); for (int col = 1; col <= 100; col++) { Console.WriteLine("This is col #" + col.ToString()); var cell = wksht.Cells[row][col] as Range; if (cell != null) { object val = cell.Value; if (val != null) { Console.WriteLine("The value of the cell is " + val.ToString()); } } } } } } } 

正如你将要处理xlsx扩展,你应该select新的连接string。

 public static string getConnectionString(string fileName, bool HDRValue, bool WriteExcel) { string hdrValue = HDRValue ? "YES" : "NO"; string writeExcel = WriteExcel ? string.Empty : "IMEX=1"; return "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + "Extended Properties=\"Excel 12.0 xml;HDR=" + hdrValue + ";" + writeExcel + "\""; } 

以上是获取连接string的代码。 第一个参数需要文件位置的实际path。 第二个参数将决定是否将第一行值视为列标题。 第三个参数有助于决定是否打开连接来创build和写入数据,或只是读取数据。 要读取数据,将其设置为“FALSE”

 public static ReadData(string filePath, string sheetName, List<string> fieldsToRead, int startPoint, int endPoint) { DataTable dt = new DataTable(); try { string ConnectionString = ProcessFile.getConnectionString(filePath, false, false); using (OleDbConnection cn = new OleDbConnection(ConnectionString)) { cn.Open(); DataTable dbSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (dbSchema == null || dbSchema.Rows.Count < 1) { throw new Exception("Error: Could not determine the name of the first worksheet."); } StringBuilder sb = new StringBuilder(); sb.Append("SELECT *"); sb.Append(" FROM [" + sheetName + fieldsToRead[0].ToUpper() + startPoint + ":" + fieldsToRead[1].ToUpper() + endPoint + "] "); OleDbDataAdapter da = new OleDbDataAdapter(sb.ToString(), cn); dt = new DataTable(sheetName); da.Fill(dt); if (dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { string i = row[0].ToString(); } } cn.Dispose(); return fileDatas; } } catch (Exception) { } } 

这是为了将2007 Excel读入数据集

  DataSet ds = new DataSet(); try { string myConnStr = ""; myConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MyDataSource;Extended Properties=\"Excel 12.0;HDR=YES\""; OleDbConnection myConn = new OleDbConnection(myConnStr); OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$] ", myConn); OleDbDataAdapter adapter = new OleDbDataAdapter(); adapter.SelectCommand = cmd; myConn.Open(); adapter.Fill(ds); myConn.Close(); } catch { } return ds;