【问题标题】:How do I upload data from an excel file to an SQL db on a web server? [closed]如何将数据从 Excel 文件上传到 Web 服务器上的 SQL 数据库? [关闭]
【发布时间】:2014-08-06 13:08:08
【问题描述】:

编辑:作业发生了巨大变化 - 抱歉。

现在我必须编写一个 Web 表单,该表单将采用 CSV 文件,然后在网格中显示其内容。仍在 C# 和 ASP.NET 中,但没有 SQL。

C#

//This is the webform
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;


namespace PatientImport
{
    public partial class WebForm1 : System.Web.UI.Page
{
    public void Page_Load(object sender, EventArgs e)
    {

        if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
        {
            string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
            string SaveLocation = Server.MapPath("Data") + "\\" + fn;
            try
            {
                if (fn.Substring(fn.Length - 3) == "csv" || fn.Substring(fn.Length - 3) == "CSV")
                {
                    File1.PostedFile.SaveAs(SaveLocation);
                    Response.Write("The file has been uploaded.");
                }
                else
                {
                    Response.Write("Incorrect type. Choose a .csv file to upload.");
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
                //Note: Exception.Message returns a detailed message that describes the current exception. 
                //For security reasons, we do not recommend that you return Exception.Message to end users in 
                //production environments. It would be better to put a generic error message. 
            }
        }
        else
        {
            Response.Write("Choose a .csv file to upload.");
        }

    }

}
}

HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"  Inherits="PatientImport.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" method="post" enctype="multipart/form-data" runat="server">
    <INPUT type=file id=File1 name=File1 runat="server" />
    <br>
    <input type="submit" id="Submit1" value="Upload" runat="server" />
    <div>
    </div>
    </form>
</body>
</html>

【问题讨论】:

  • 我只想让您的应用程序调用一个 Web 方法,该方法在文件上传后将数据加载到 SQL 中。
  • 您有什么问题?上传文件?解析文件?
  • 如果没有看到您的原始代码,我们将不知道如何对您现有的代码库进行更改。请发帖a minimal example of what needs to change,并详细说明需要修改的地方。
  • 正如@gunr2171 所说,您应该发布a minimal example of what needs to change。如果没有看到一些代码,我们就无法帮助您,因为我们不知道您要做什么。
  • 请再看一遍,我加了代码,赋值变了。

标签: c# asp.net csv datagrid webforms


【解决方案1】:

Should the program be separate from the web form application that accepts the file? - 这取决于你的需要。您可以将其分开,或者您的 Web 应用程序可以这样做。

How do I get the program to run on the web server right when a file is uploaded? - 如果这是由您的 Web 应用程序完成的,您将在上传完成后立即执行此操作。如果您决定让您的桌面应用程序传输到 db,请使用 FileSystemWatcher 类来查看您在网络服务器上将 Excel 文件上传到的目录。

【讨论】:

    【解决方案2】:

    使用 ASP.NET 网格,一切皆有可能。

    HTML

    <asp:gridview id="CSVGridView" runat="server" />
    

    C#

    //This is the webform
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.IO;
    using System.Text.RegularExpressions;
    
    
    namespace PatientImport {
        public partial class WebForm1: System.Web.UI.Page {
            public void Page_Load(object sender, EventArgs e) {
                if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0)) {
                    string fn = Path.GetFileName(File1.PostedFile.FileName);
                    string SaveLocation = Server.MapPath("Data") + "\\" + fn;
    
                    try {
                        if (fn.Substring(fn.Length - 3) == "csv" || fn.Substring(fn.Length - 3) == "CSV") {
                            File1.PostedFile.SaveAs(SaveLocation);
                            Response.Write("The file has been uploaded.");
    
                            // Read and parse the file
                            string[] data = File.ReadAllLines(SaveLocation);
                            string pattern = "\"(?<data>.*?)\"|(^|,)(?<data>[^,\r\n]*)";
                            RegexOptions options = RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.ECMAScript;
    
                            DataTable dt = new DataTable();
    
                            MatchCollection matches = Regex.Matches(data[0], pattern, options);
    
                            foreach (Match match in matches) {
                                dt.Columns.Add(match.Groups["data"].Value, typeof(string));
                            }
    
                            for (int i = 1; i < data.Length; i++) {
                                matches = Regex.Matches(data[i], pattern, options);
    
                                List<string> row = new List<string>();
    
                                foreach (Match match in matches) {
                                    row.Add(match.Groups["data"].Value);
                                }
    
                                dt.Rows.Add(row.ToArray());
                            }
    
                            CSVGridView.DataSource = dt;
                            CSVGridView.DataBind();
                        } else {
                            Response.Write("Incorrect type. Choose a .csv file to upload.");
                        }
                    } catch (Exception ex) {
                        Response.Write("Error: " + ex.Message);
                        //Note: Exception.Message returns a detailed message that describes the current exception. 
                        //For security reasons, we do not recommend that you return Exception.Message to end users in 
                        //production environments. It would be better to put a generic error message. 
                    }
                } else {
                    Response.Write("Choose a .csv file to upload.");
                }
            }
        }
    }
    

    说明

    我正在使用正则表达式"(?&lt;data&gt;.*?)"|(^|,)(?&lt;data&gt;[^,\r\n]*):

    1. "(?&lt;data&gt;.*?)" 匹配一个引号,任何字符 0 次或多次(? 使其不贪婪,因此当它到达另一个引号时它将停止匹配)和一个引号。

      ".*?" 将匹配所有 "abc",因此我们通过创建捕获组 ((?&lt;data&gt;.*?)) 仅选择 abc 部分。

    2. (^|,)(?&lt;data&gt;[^,\r\n]*) 匹配行首或逗号,然后匹配除逗号、回车或换行以外的任何字符,一次或多次。

      同样,(?&lt;data&gt; 启动了一个名为 data 的捕获组,这样我们就不会得到逗号(如果有的话)。

    然后,在代码中,我使用match.Groups["data"].Value 来获取命名捕获组data 的值。

    对于标志,我使用ECMAScript,以便可以使用 ECMAScript 定义的语义。使用ECMAScript 标志需要其他标志:Compiled、Multiline 和IgnoreCase。

    【讨论】:

    • 谢谢,我试试
    • 好的@toothbrush,所以它告诉我两个 foreach 循环内的 Add 方法不能接受 match.Groups["data"] 作为字符串。
    • @SavageHenry 好的,我想我现在已经更正了。请再试一次好吗?
    • 是的!成功了,谢谢!您介意向我解释一下字符串模式和 RegexOptions 的作用吗? @牙刷
    • @SavageHenry 我在帖子中添加了解释。如果它没有说明它的作用,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 2017-12-09
    • 1970-01-01
    • 2013-12-24
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多