如何从HttpPostedfile中读取excel文件 [英] How can I read excel file from HttpPostedfile

查看:851
本文介绍了如何从HttpPostedfile中读取excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现以下目标



1.我想通过网页将Excel文件上传到服务器。

2。上传的文件不会被写入物理存储器,而是后面的代码将从流(httppostedfile)中读取数据,然后再将其上传到MSSQL服务器。

3。将xls文件写入服务器可能会遇到权限错误。如果允许,文件将占用存储空间而不再使用。



我还没有看到像直接从流中读取的方法。

我找到的所有内容都是将其写入phsycal文件(c:\ xxx \ xx.xls)然后阅读内容。



如何在不将文件写入文件夹的情况下读取列?

I want to achieve the following

1. I want to upload an excel file to Server through web page.
2. the uploaded file will not be written to physical storage,
instead the code behind will read the data from a stream(httppostedfile) before uploading it to MSSQL server.
3. Writing the xls file to server might encounter a permission error. Incase if it is allowed, the files will occupy space in the storage without any use anymore.

I have not seen an approach like direct reading from stream.
All i found is to write it to phsycal file (c:\xxx\xx.xls) and then read the content.

How can I read the columns without writing the file to a folder?

推荐答案

这是一个显示如何从中创建DataTable的示例使用EPPlus的HttpPostedFile的IO.Stream:



Here''s an example which shows how to create a DataTable from the IO.Stream of a HttpPostedFile using EPPlus:

protected void UploadButton_Click(Object sender, EventArgs e)
{
    if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".xlsx")
    {
        using (var excel = new ExcelPackage(FileUpload1.PostedFile.InputStream))
        {
            var tbl = new DataTable();
            var ws = excel.Workbook.Worksheets.First();
            var hasHeader = true;  // adjust accordingly
            // add DataColumns to DataTable
            foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
                tbl.Columns.Add(hasHeader ? firstRowCell.Text
                    : String.Format("Column {0}", firstRowCell.Start.Column));

            // add DataRows to DataTable
            int startRow = hasHeader ? 2 : 1;
            for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
            {
                var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
                DataRow row = tbl.NewRow();
                foreach (var cell in wsRow)
                    row[cell.Start.Column - 1] = cell.Text;
                tbl.Rows.Add(row);
            }
            var msg = String.Format("DataTable successfully created from excel-file. Colum-count:{0} Row-count:{1}",
                                    tbl.Columns.Count, tbl.Rows.Count);
            UploadStatusLabel.Text = msg;
        }
    }
    else 
    {
        UploadStatusLabel.Text = "You did not specify a file to upload.";
    }
}





我已经检查了这个,它对我有用。



I have checked for this and it is working for me.


这篇关于如何从HttpPostedfile中读取excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆