asp.net实现导入excel表格

最近接到了一个实习任务,写一个可以从web页面上导入表格信息并下载成excel文件的demo

ps:博主刚参加实习,有过一段java编写的经验….


首先页面是通过html代码实现的,而数据信息是通过从数据库查找显示在页面上的。
先开始建一个WebForm

博主这里对.net确实不太熟悉,直接建了个WebApi,但并没有用控制器,直接在*.aspx.cs里写逻辑代码,这里就将错就错吧。

在aspx前台创建一个表格,里面先填上数据,页面做的比较简陋,情况如下图:
这里写图片描述

给Downloading添加OnClick事件:
这里写图片描述
在后开给Downloading添加事件绑定:`

protected void hidExport_Click(object sender, System.EventArgs e)
        {
            string content = getExcelContent();
            string filename = "Test.xls";
            CommonTool.ExportToExcel(filename, content);
        }`

content的获取写成一个getExcelContent()函数,主要功能是获取当前页面的html代码转换成string类型返回,具体的代码如下:

 public static string getExcelContent()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(getMessages.GetHtmlString(getMessages.GetCurrentUrl()));
            return sb.ToString();
        }

考虑到在真实环境中页面的信息会发生改变,这里采用StringBuilder对象来接受获取到的(操作速度快,字符长度可变),具体的String,StringBuilder,StringBuffer的区别请参考这个博客

public static class getMessages
{
    public static string GetCurrentUrl()
    {
        string uri = HttpContext.Current.Request.Url.ToString();
        return uri;
    }
    public static string GetHtmlString(string url)
    {
        WebRequest wr = WebRequest.CreateHttp(url);
        WebResponse res = wr.GetResponse();
        Stream st = res.GetResponseStream();
        StreamReader sr = new StreamReader(st, Encoding.UTF8);
        string GetHtml = sr.ReadToEnd();
        st.Close();
        sr.Close();
        return GetHtml;
    }

content就是将要输出给用户的文本内容,不过在传送之前要将html改变成excel的格式,转换的代码如下:

res.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
res.ContentType = "application/vnd.ms-excel;charset=UTF-8";

对于用户下载的操作,这里博主参考了网上的做法,具体代码是通过缓存输出到客户端的:

  public class CommonTool
        {
            public static void ExportToExcel(string filename, string content)
            {
                var res = HttpContext.Current.Response;
                res.Clear();
                res.Buffer = true;
                res.Charset = "UTF-8";
                res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                res.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                res.ContentType = "application/vnd.ms-excel;charset=UTF-8";
                res.Write(content.Replace("<td","<td STYLE='MSO-NUMBER-FORMAT:\\@'"));
                res.Flush();
                res.End();

            }
        }

这里差一插话,当数字过长时excel会自动转换成科学计数法,这样如果我需要输入一个身份证号,就出现了bug:
这里写图片描述
所以博主将content里的<td都用了<td STYLE='MSO-NUMBER-FORMAT:\\@'代替,其中 STYLE=’MSO-NUMBER-FORMAT:\@’是excel中的文本格式,这样就避免了以上问题。

运行后下载的excel如下图:
这里写图片描述


整体的代码在下面贴出:

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1.Models
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void hidExport_Click(object sender, System.EventArgs e)
        {
            string content = getExcelContent();
            string filename = "Test.xls";
            CommonTool.ExportToExcel(filename, content);
        }
        //设置http头部信息,并输出到客户端
        public class CommonTool
        {
            public static void ExportToExcel(string filename, string content)
            {
                var res = HttpContext.Current.Response;
                res.Clear();
                res.Buffer = true;
                res.Charset = "UTF-8";
                res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                res.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                res.ContentType = "application/vnd.ms-excel;charset=UTF-8";
                res.Write(content.Replace("<td","<td STYLE='MSO-NUMBER-FORMAT:\\@'"));
                res.Flush();
                res.End();

            }
        }
        public static string getExcelContent()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(getMessages.GetHtmlString(getMessages.GetCurrentUrl()));
            return sb.ToString();
        }

    }
}
public static class getMessages
{
    public static string GetCurrentUrl()
    {
        string uri = HttpContext.Current.Request.Url.ToString();
        return uri;
    }
    public static string GetHtmlString(string url)
    {
        WebRequest wr = WebRequest.CreateHttp(url);
        WebResponse res = wr.GetResponse();
        Stream st = res.GetResponseStream();
        StreamReader sr = new StreamReader(st, Encoding.UTF8);
        string GetHtml = sr.ReadToEnd();
        st.Close();
        sr.Close();
        return GetHtml;

    }
}

ps:后发现一般web页面上都有分页功能,所以这个demo只是练手,实际并不实用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET MVC导入Excel文件到数据库功能可以通过以下步骤实现: 1. 创建一个控制器和视图来上传Excel文件。 2. 使用第三方库如EPPlus来解析Excel文件并将其转换为数据表。 3. 使用ADO.NET连接到数据库并将数据表中的数据插入到数据库中。 以下是一个示例控制器和视图的代码: 控制器: ``` public class ExcelController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Import(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { string fileName = Path.GetFileName(file.FileName); string fileExtension = Path.GetExtension(fileName); if (fileExtension == ".xls" || fileExtension == ".xlsx") { string filePath = Server.MapPath("~/Content/" + fileName); file.SaveAs(filePath); DataTable dt = ReadExcelFile(filePath); InsertDataIntoDatabase(dt); return RedirectToAction("Index"); } else { ViewBag.Message = "Please upload a valid Excel file."; return View("Index"); } } else { ViewBag.Message = "Please select an Excel file to upload."; return View("Index"); } } private DataTable ReadExcelFile(string filePath) { using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; DataTable dt = new DataTable(); bool hasHeaderRow = true; foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column]) { dt.Columns.Add(hasHeaderRow ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column)); } int startRow = hasHeaderRow ? 2 : 1; for (int rowNum = startRow; rowNum <= worksheet.Dimension.End.Row; rowNum++) { var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column]; DataRow row = dt.Rows.Add(); foreach (var cell in wsRow) { row[cell.Start.Column - 1] = cell.Text; } } return dt; } } private void InsertDataIntoDatabase(DataTable dt) { string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES (@Column1, @Column2, @Column3)"; foreach (DataRow row in dt.Rows) { command.Parameters.AddWithValue("@Column1", row["Column1"]); command.Parameters.AddWithValue("@Column2", row["Column2"]); command.Parameters.AddWithValue("@Column3", row["Column3"]); command.ExecuteNonQuery(); command.Parameters.Clear(); } } } } ``` 视图: ``` @{ ViewBag.Title = "Import Excel File"; } <h2>Import Excel File</h2> @using (Html.BeginForm("Import", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-group"> <label for="file">Select Excel File:</label> <input type="file" name="file" id="file" /> </div> <button type="submit" class="btn btn-primary">Import</button> <div class="alert alert-danger" role="alert">@ViewBag.Message</div> } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值