如何使Web服务读取文件?

时间:2013-07-15 05:49:35

标签: c# asp.net sql web-services

我正在创建一个Web服务,它应该读取一个excel文件,并返回一个SQL表,其中包含相应列中excel表的所有值。这是我的网络服务的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;

namespace FileUploader
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string simple()
        {
            return "Hello World";
        }
        [WebMethod]
        private string cleaner(string query)
        {
            query = query.Replace("'", "");
            query = query.Replace("\\", "");
            query = query.Replace("/", "");
            query = query.Replace("\"", "");
            query = query.Replace(".", "");
            query = query.Replace(";", ",");
            return query;
        }
        [WebMethod]
        private string insertinsql(string query)
        {
            string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\Users\Sagnik\documents\visual studio 2010\Projects\FileUploader\FileUploader\App_Data\Database1.mdf"";Integrated Security=True;User Instance=True";
            SqlConnection con = new SqlConnection(constr);
            try
            {
                con.Open();
            }
            catch (Exception e)
            {
                return e.ToString();
            }
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Connection = con;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                return e.ToString();
            }
            con.Close();
            return "1";
        }

        [WebMethod]
        public string upload(string file)
        {
            //string path = Path.GetFullPath(file);
            System.Data.DataTable dt = null;
            string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + file + "';Extended Properties= 'Excel 8.0;HDR=No;IMEX=1'";
            OleDbConnection con = new OleDbConnection(SourceConstr);
            try
            {
                con.Open();
            }
            catch(Exception e)
            {
                return e.ToString();
            }
            dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            {
                return "dt was null";
            }
            String[] excelSheets = new String[dt.Rows.Count];
            int sh = 0;
            foreach (DataRow row in dt.Rows)
            {
                if (row["TABLE_NAME"].ToString().Contains("$"))
                {
                    excelSheets[sh] = row["TABLE_NAME"].ToString();
                    sh++;
                }
            }
            int count = 0;
            for (int z = 0; z < sh; z++)
            {
                if (!excelSheets[z].ToString().Contains("Print_Area"))
                {
                    count = 0;
                    string query = "SELECT top 1 * FROM [" + excelSheets[z] + "];";
                    OleDbCommand command = new OleDbCommand(query, con);
                    OleDbDataReader odr = command.ExecuteReader();
                    string[] names = new string[50];
                    while (odr.Read())
                    {
                        count = odr.FieldCount;
                        int i = 0;
                        while (i < count)
                        {
                            names[i] = cleaner(odr[i].ToString()).Replace(" ", "");
                            i += 1;
                        }
                        break;
                    }
                    int j = 0;
                    string name = Path.GetFileNameWithoutExtension(file);
                    query = "CREATE TABLE " + cleaner(name) + "_" + cleaner(excelSheets[z]).Replace(" ", "").Replace("$", "") + " ( ";
                    for (int i = 0; i < count; i++)
                    {
                        if (names[i] != "")
                        {
                            query += (names[i] + " VARCHAR(100), ");
                            j += 1;
                        }
                    }
                    if (query.Contains("VARCHAR(100)"))
                    {
                        count = j;
                        query = query.Substring(0, query.Length - 2);
                        query = query + ");";
                        string checker = insertinsql(query);
                        if (checker != "1")
                        {
                            return checker;
                        }
                        odr.Close();
                        string src = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + file + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
                        OleDbConnection conn = new OleDbConnection(src);
                        conn.Open();
                        string q = "SELECT * FROM [" + excelSheets[z] + "];";
                        OleDbCommand cmd = new OleDbCommand(q, conn);
                        odr = cmd.ExecuteReader();
                        int check = 1;
                        while (odr.Read())
                        {
                            query = "INSERT INTO " + cleaner(name) + "_" + cleaner(excelSheets[z]).Replace(" ", "").Replace("$", "") + " (";
                            for (int i = 0; i < count; i++)
                            {
                                query += (names[i] + ", ");
                            }
                            query = query.Substring(0, query.Length - 2);
                            query += ") VALUES (";
                            for (int i = 0; i < count; i++)
                            {
                                query += ("'" + cleaner(odr[i].ToString()) + "', ");
                            }
                            query = query.Substring(0, query.Length - 2);
                            query += ");";
                            if (check == 1)
                            {
                                insertinsql(query);
                            }
                            else
                            {
                                return "Error";
                            }
                        }
                        conn.Close();
                    }
                }
            }
            con.Close();
            return "Copy Successful...Tables Saved As " + Path.GetFileNameWithoutExtension(file);
        }
    }
}

这是一个使用Web服务的测试应用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TestUploader.testweb;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.FileName == "")
            {
                return;
            }
            else if (System.IO.Path.GetExtension(FileUpload1.FileName).ToString() != ".xls" && System.IO.Path.GetExtension(FileUpload1.FileName).ToString() != ".xlsx")
            {
                Response.Write("<script type='text/javascript'>alert('Please Upload A Valid Excel File');</script>");
                return;
            }
            else
            {
                Label1.Text = "Please Wait...Copying Data";
                Service1 ser = new Service1();
                string path = SaveFile(FileUpload1.PostedFile);//System.IO.Path.GetFullPath(FileUpload1.FileName);
                string s = ser.upload(path);
                Label1.Text = s;
            }
        }

        string SaveFile(HttpPostedFile file)
        {
            // Specify the path to save the uploaded file to.
            string savePath = "c:\\Apps\\Uploads\\";

            // Get the name of the file to upload.
            string fileName = FileUpload1.FileName;

            // Create the path and file name to check for duplicates.
            string pathToCheck = savePath + fileName;

            // Create a temporary file name to use for checking duplicates.
            string tempfileName = "";

            // Check to see if a file already exists with the
            // same name as the file to upload.        
            if (System.IO.File.Exists(pathToCheck))
            {
                int counter = 2;
                while (System.IO.File.Exists(pathToCheck))
                {
                    // if a file with this name already exists,
                    // prefix the filename with a number.
                    tempfileName = System.IO.Path.GetFileNameWithoutExtension(fileName) + counter.ToString() + System.IO.Path.GetExtension(fileName);
                    pathToCheck = savePath + tempfileName;
                    counter++;
                }

                fileName = tempfileName;

                // Notify the user that the file name was changed.
            }
            else
            {
                // Notify the user that the file was saved successfully.

            }

            // Append the name of the file to upload to the path.
            savePath += fileName;

            // Call the SaveAs method to save the uploaded
            // file to the specified directory.
            FileUpload1.SaveAs(savePath);
            return savePath;

        }

    }
}

此代码运行正常,但它将文件上载到Web服务,并在Web服务中创建数据库。现在,我被告知,在使用网络服务时,我们无法继续上传文件,因为网络服务可能无法访问。我可以将excel文件作为数据行上传,但是所有工作都将由客户端程序完成,我希望Web服务尽可能方便用户使用。

所以,我有两个问题:

  1. 有没有更好的方法来完成这项工作而无需将文件上传到网络服务?

  2. 由于必须在客户端程序的数据库中创建表,我想将所有查询附加到同一个字符串中,并将字符串返回给客户端程序,然后它可以在sql server manager。再次,有没有更好的方法使这个用户更友好?

  3. 提前致谢!

0 个答案:

没有答案