0

感谢您的阅读,我的疑问如下,我试图从 xls 文件中获取数据,但必须在本地完成,无需上传文件,我已经完成了与 txts 文件类似的操作,并且效果很好:

Function Send(ByVal file As HttpPostedFileBase) As ActionResult
    Dim line As String
    Dim textreader As System.IO.StreamReader = New StreamReader(file.InputStream)
    While Not textreader.EndOfStream
        line = textreader.ReadLine()
        ViewBag.line = line
    End While
    Return View("Index")
End Function

但我不能对excel文件做同样的事情,首先,因为我不能使用streamreader,所以在使用这段代码时我不知道如何指定我的xls文件的目录

    Dim oApp As Excel.Application = New Excel.Application
    Dim oWB As Excel.Workbook
    Dim oSheet As Excel.Worksheet
    oWB = oApp.Workbooks.Open(file.inputstream)  <-- HERE IS WHERE I GET (AN OBVIOUS) ERROR

有人知道如何在本地打开文件吗?谢谢阅读 :)

4

1 回答 1

0

有几种方法可以做到这一点,其中一种是访问文件“数据库样式”......

...
    string filePath = string.Format("C:\\TEST\\{0}.xlsx", Guid.NewGuid().ToString());
    var fileStream = File.Create(filePath);
    input.CopyTo(file.InputStream);
    fileStream.Close();

    string cn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath  + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
    string query = "SELECT * FROM SHEET_NAME";

    conn= new OleDbConnection(cn);
    conn.Open();
    OleDbCommand woOleCommand = new OleDbCommand(query, conn);

    DbDataReader result = woOleCommand.ExecuteReader();

    // Read the DataReader...
...

所以基本上你像表格一样查询表格,如果它们确实是表格,那么这段代码可能就是你要找的。

另一方面,如果您仍需要使用自动化,请尝试以下方法:

...    
object missing = System.Reflection.Missing.Value;
wBook = (Excel._Workbook)xl.Workbooks.Open(filePath, false, false, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); 
...

读取输入流

using (var fileStream = File.Create(filePath)) {
     file.InputStream.CopyTo(fileStream); 
} 
// Now you got your stream on a file (filePath) so you can work with it.
于 2012-07-19T20:06:09.583 回答