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

时间:2015-07-24 17:57:25

标签: c# azure azure-storage azure-storage-blobs

我有一个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

Upload Excel File and Extract Data from it and put that data in database using MVC asp.net

做我的申请。但是,网站http://www.codeproject.com/Tips/752981/Import-Data-from-Excel-File-to-Database-Table-in-A中的示例允许用户将文件上传到部署应用程序而不是Azure存储的Web服务器,并且“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?
        }  

        ...  

1 个答案:

答案 0 :(得分:0)

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

下载:

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

使用批量复制将数据插入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();
 }