简体   繁体   English

如何上传Excel文件并添加列到数据库?

[英]how to upload excel file and add columns into database?

i'm using open xml sdk dll in my Asp net MVC for uploading excel into my website. 我在Asp net MVC中使用开放的XML sdk dll将excel上载到我的网站。

there is 4 column in my excel file Name , Email , Company Name and Phone Number. 我的excel文件中有4列Name,Email,Company Name和Phone Number。

i use following code to get excel file from my view and save it in local disk and then access to it's cell for saving in my database. 我使用以下代码从我的视图中获取excel文件,并将其保存在本地磁盘中,然后访问它的单元格以保存在数据库中。

**but there is problem in debugging the code. **但是在调试代码时有问题。 when i want to access cell that contain string it shows me it contains 0 but there is no problem in reading numbers. 当我想访问包含字符串的单元格时,显示它包含0,但读取数字没有问题。

it shows zero when my foreach item goes on cells that contains string .** any idea's? 当我的foreach项进入包含字符串的单元格时,它显示为零。**有任何想法吗?

edited Question: i managed to read cell's value with this code modification but there is another problem.according to This answer i should read shared string to read string but when i read DataType , it valued null in some random moment. 编辑的问题:通过此代码修改,我设法读取了单元格的值,但是还有另一个问题。根据此答案,我应该读取共享字符串以读取字符串,但是当我读取DataType时,它在某个随机时刻的值为null。 so i cant read some cell's. 所以我看不懂一些细胞。 i cant find the problem 我找不到问题

here is controller code: 这是控制器代码:

    [HttpPost]
    public IHttpActionResult UploadExcelFile()
    {
        try
        {
            var rnd = new Random();
            string filePath = "";
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count < 1)
            {
                return Content(HttpStatusCode.BadRequest, "there's no file selected");
            }

            var guid = rnd.Next(999);
            var postedFile = httpRequest.Files[0];
            var serverFilePath = HttpContext.Current.Server.MapPath("~/Content/Email/" + guid + Path.GetExtension(postedFile.FileName));
            filePath = "/Content/Email/" + guid + Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(serverFilePath);


            using (SpreadsheetDocument spreadsheetDocument =SpreadsheetDocument.Open(serverFilePath, false))
            {
                List<string> colName = new List<string>(new string[] { "A", "B", "C","D" });

                var sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>();
                WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
                WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                Worksheet worksheet = worksheetPart.Worksheet;
                var rowCount = GetRowCount(worksheet);
                for (int i = 0; i < rowCount; i++)
                {  
                    Cell cell = GetCell(worksheet, colName[i], i+1);
                    Row row = GetRow(worksheet, i+1);
                    foreach (var item in row.ChildElements)
                    {
                        List<string> cellValue = new List<string>();

                        if (cell.DataType != null)
                        {
                            if (cell.DataType == CellValues.SharedString)
                            {
                                int id = -1;

                                if (Int32.TryParse(cell.InnerText, out id))
                                {
                                    SharedStringItem x = GetSharedStringItemById(workbookPart, id);

                                    if (x.Text != null)
                                    {
                                        cellValue.Add(x.Text.Text);
                                    }
                                    else if (item.InnerText != null)
                                    {
                                        cellValue.Add(x.InnerText);
                                    }
                                    else if (item.InnerXml != null)
                                    {
                                        cellValue.Add(x.InnerXml);
                                    }
                                }
                            }
                        }
                        else
                        {
                            cellValue.Add(item.InnerText);
                        }


                    }

                }



            }


            return Ok(new { message = "Record has been saved successfully" });
        }
        catch (Exception e)
        {
            return Content(HttpStatusCode.BadRequest, "there's problem with Server");

            throw;
        }
    }
        var connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\mybook.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1;\"";


        var OledbConn = new OleDbConnection(connString);

        DataTable schemaTable = new DataTable();
        var OledbCmd = new OleDbCommand();
        OledbCmd.Connection = OledbConn;
        OledbConn.Open();
        OledbCmd.CommandText = "Select * from [StudentDetails$]";
        OleDbDataReader dr = OledbCmd.ExecuteReader();
        DataTable ContentTable = null;
        if (dr.HasRows)
        {
            ContentTable = new DataTable();
            ContentTable.Columns.Add("Name", typeof(string));
            ContentTable.Columns.Add("Email", typeof(string));
            ContentTable.Columns.Add("Company Name", typeof(string));
            ContentTable.Columns.Add("Phone Number", typeof(string));
            while (dr.Read())
            {
                if (dr[0].ToString().Trim() != string.Empty && dr[1].ToString().Trim() != string.Empty && dr[2].ToString().Trim() != string.Empty && dr[0].ToString().Trim() != " " && dr[1].ToString().Trim() != " " && dr[2].ToString().Trim() != " ")
                    ContentTable.Rows.Add(dr[0].ToString().Trim(), dr[1].ToString().Trim(), dr[2].ToString().Trim(), dr[3].ToString().Trim());

            }
        }
        dr.Close();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM