Tôi đã gặp sự cố tương tự nhưng tôi không muốn chuyển sang dịch vụ trả tiền, vì vậy đây là những gì tôi đã làm.
public class DataImportHelper : IDisposable
{
private readonly string _fileName;
private readonly string _tempFilePath;
public DataImportHelper(HttpPostedFileBase file, string tempFilePath)
{
_fileName = file.FileName;
_tempFilePath = Path.Combine(tempFilePath, _fileName);
(new FileInfo(_tempFilePath)).Directory.Create();
file.SaveAs(_tempFilePath);
}
public IQueryable<T> All<T>(string sheetName = "")
{
if (string.IsNullOrEmpty(sheetName))
{
sheetName = (typeof (T)).Name;
}
var excelSheet = new ExcelQueryFactory(_tempFilePath);
return from t in excelSheet.Worksheet<T>(sheetName)
select t;
}
public void Dispose()
{
File.Delete(_tempFilePath);
}
}
Đây là một thử nghiệm
[Fact]
public void AcceptsAMemoryStream()
{
MemoryFile file;
using (var f = File.OpenRead("SampleData.xlsx"))
{
file = new MemoryFile(f, "multipart/form-data", "SampleData.xlsx");
using (var importer = new DataImportHelper(file, "Temp/"))
{
var products = importer.All<Product>();
Assert.NotEmpty(products);
}
}
}
Đây là MemoryFile.cs. Tệp này chỉ được sử dụng để thử nghiệm. Nó chỉ là một thực hiện của HttpPostedFileBase vì vậy bạn có thể kiểm tra bộ điều khiển của bạn và trợ giúp nhỏ của tôi. Điều này đã được mượn từ một bài đăng khác.
public class MemoryFile : HttpPostedFileBase
{
Stream stream;
string contentType;
string fileName;
public MemoryFile(Stream stream, string contentType, string fileName)
{
this.stream = stream;
this.contentType = contentType;
this.fileName = fileName;
}
public override int ContentLength
{
get { return (int)stream.Length; }
}
public override string ContentType
{
get { return contentType; }
}
public override string FileName
{
get { return fileName; }
}
public override Stream InputStream
{
get { return stream; }
}
public override void SaveAs(string filename)
{
using (var file = File.Open(filename, FileMode.Create))
stream.CopyTo(file);
}
}
Nguồn
2012-12-20 18:41:53
có thể trùng lặp của câu hỏi này: [đọc file excel từ một dòng] (http: // stackoverflow .com/questions/560435/read-excel-file-from-a-stream)? –
Bạn sẽ phải xem xét các vấn đề như: Điều gì sẽ xảy ra nếu bảng không có trên trang tính đầu tiên? Điều gì xảy ra nếu nó không nằm trong phạm vi bạn chỉ định? Excel không có khả năng OleDb, nhưng bạn phải sử dụng các phương thức như 'GetOleDbSchema()' để nhận các tab, sau đó biết phạm vi truy vấn. Có thể, nhưng không chỉ 3 dòng mã. –
@DominicZukiewicz Đó không phải là vấn đề thực sự trong trường hợp của tôi vì mỗi tệp tải lên sẽ có cùng một lược đồ. – MuriloKunze