繁体   English   中英

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

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

我有一个MVC Web应用程序,该应用程序允许用户将Excel文件上传到Azure云存储,然后该应用程序使用该Azure存储的Excel Blob文件将数据导入SQL Server。

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

上载Excel文件并从中提取数据,然后使用MVC asp.net将数据放入数据库中

做我的申请。 但是,来自站点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 “

我的问题 :对于Azure存储Excel Blob文件,如何指定“ fileLocation”和“ excelConnectionString”变量的值? 请参阅以“ // ***开头的短语”的代码注释。如何使用Azure存储代码来做到这一点? 下面。

来自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?
        }  

        ...  

也许您可以先将Azure的Blob文件下载到服务器磁盘,然后再将其导入数据库。 您可以在此处下载完整的项目。

下载:

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

将文件读取到数据表:

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);
    }
}

使用批量复制将数据插入数据库

 //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