简体   繁体   English

从Azure Excel Blob文件将数据导入SQL Server

[英]Import data into SQL Server from an Azure Excel blob file

I have an MVC web application that allows user to upload an Excel files to Azure cloud storage, and then the application uses that Azure-stored Excel blob file to import data into SQL Server. 我有一个MVC Web应用程序,该应用程序允许用户将Excel文件上传到Azure云存储,然后该应用程序使用该Azure存储的Excel Blob文件将数据导入SQL Server。

I follow the sites http://www.codeproject.com/Tips/752981/Import-Data-from-Excel-File-to-Database-Table-in-A 我遵循以下网站:http://www.codeproject.com/Tips/752981/Import-Data-from-Excel-File-to-Database-Table-in-A

and

Upload Excel File and Extract Data from it and put that data in database using MVC asp.net 上载Excel文件并从中提取数据,然后使用MVC asp.net将数据放入数据库中

to do my application. 做我的申请。 However, the example from the site http://www.codeproject.com/Tips/752981/Import-Data-from-Excel-File-to-Database-Table-in-A lets users upload file to web server where application is deployed not Azure storage , and the contents of "fileLocation" variable (please see the below codes) looks like (relative to web-server-hosted application path C or whatever drive) "C:\\MyWebApplicationFolder\\MyApplicatioName\\Content\\Excel_blob.xlsx" 但是,来自站点http://www.codeproject.com/Tips/752981/Import-Data-from-Excel-File-to-Database-Table-in-A的示例允许用户将文件上传到应用程序所在的Web服务器部署而不是Azure存储 ,并且“ fileLocation”变量的内容(请参见以下代码)看起来像(相对于Web服务器托管的应用程序路径C或任何驱动器) “ C:\\ MyWebApplicationFolder \\ MyApplicatioName \\ Content \\ Excel_blob.xlsx “

My question : for Azure storage Excel blob files, how can I specify the value of "fileLocation" and "excelConnectionString" variables? 我的问题 :对于Azure存储Excel Blob文件,如何指定“ fileLocation”和“ excelConnectionString”变量的值? Please see my code comments starting with phrase "// *** How can I can do this with Azure storage codes?" 请参阅以“ // ***开头的短语”的代码注释。如何使用Azure存储代码来做到这一点? below. 下面。

Codes from http://www.codeproject.com/Tips/752981/Import-Data-from-Excel-File-to-Database-Table-in-A 来自http://www.codeproject.com/Tips/752981/Import-Data-from-Excel-File-to-Database-Table-in-A中的代码

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    DataSet ds = new DataSet();
    if (Request.Files["file"].ContentLength > 0)
    {
        string fileExtension =  System.IO.Path.GetExtension(Request.Files["file"].FileName);

        if (fileExtension == ".xls" || fileExtension == ".xlsx")
        {
            string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;  // *** How can I can do this with Azure storage codes?

        if (System.IO.File.Exists(fileLocation))
        {
            System.IO.File.Delete(fileLocation);
        }
        Request.Files["file"].SaveAs(fileLocation);
        string excelConnectionString = string.Empty;

        excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +     fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";  // *** How can I can do this with Azure storage codes?


        //connection String for xls file format.
        if (fileExtension == ".xls")
        {
            excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +   fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";     // *** How can I can do this with Azure storage codes?
        }
        //connection String for xlsx file format.
        else if (fileExtension == ".xlsx")
        {
            excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +   fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";     // *** How can I can do this with Azure storage codes?
        }  

        ...  

Maybe you can download blob file from Azure to your server disk first and then import it to your db. 也许您可以先将Azure的Blob文件下载到服务器磁盘,然后再将其导入数据库。 You can download the full project here . 您可以在此处下载完整的项目。

Downloading: 下载:

container.CreateIfNotExists();
CloudBlockBlob blob = container.GetBlockBlobReference(excelName);
blob.DownloadToFile(filePath, FileMode.Create);

Read the file to data table: 将文件读取到数据表:

DataTable dt = new DataTable();
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filePath, false))
{
    //Get sheet data
    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
    string relationshipId = sheets.First().Id.Value;
    WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
    Worksheet workSheet = worksheetPart.Worksheet;
    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
    IEnumerable<Row> rows = sheetData.Descendants<Row>();

    // Set columns
    foreach (Cell cell in rows.ElementAt(0))
    {
        dt.Columns.Add(cell.CellValue.InnerXml);
    }

    //Write data to datatable
    foreach (Row row in rows.Skip(1))
    {
        DataRow newRow = dt.NewRow();
        for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
        {
            if (row.Descendants<Cell>().ElementAt(i).CellValue != null)
            {
                newRow[i] = row.Descendants<Cell>().ElementAt(i).CellValue.InnerXml;
            }
            else
            {
                newRow[i] = DBNull.Value;
            }
        }
        dt.Rows.Add(newRow);
    }
}

Use bulk copy to insert the data to db 使用批量复制将数据插入数据库

 //Bulk copy datatable to DB
 SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionStr);
 try
 {
     columns.ForEach(col => { bulkCopy.ColumnMappings.Add(col, col); });
     bulkCopy.DestinationTableName = tableName;
     bulkCopy.WriteToServer(dt);
 }
 catch (Exception ex)
 {
     throw ex;
 }
 finally
 {
     bulkCopy.Close();
 }

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

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