2017-03-23 12 views
3

WebApiにExcelファイルをアップロードしようとしていて、その内容でSTUFFを実行しようとしています。 アップロードボタンを使ってファイルを送信しているextJsの部分が完成しました。 (以下のコード)ExcelファイルをWeb APIにアップロード

私の問題は、私は、Excelファイルを処理するためにWEBAPI部分を構築する方法がわからないです。私はHttpPostを持っていなければならないと思っています。

フェイクWEBAPI:

public string SampleUploadFile() 
{ 
    return _repo.UploadFile(); 
} 

ExtJSのコード:

xtype: 'form', 
//renderTo: 'fi-form', //(5) 
fileUpload: true, //(1) 
width: 500, 
frame: true, 
title: 'Position Sheet Upload Form', 
bodyPadding: '10 10 0', 
//bodyStyle: 'padding: 10px 10px 0 10px;', 

defaults: { 
    anchor: '100%', 
    allowBlank: false, 
    msgTarget: 'side', 
    labelWidth: 50 
}, 

//labelWidth: 50, 
items: [{ 
    xtype: 'fileuploadfield', 
    emptyText: 'Select an image', 
    fieldLabel: 'Image', 
    name: 'file', //(2) 
    buttonText: 'Choose a file' 
}], 
buttons: [{ 
    text: 'Save', 
    handler: function() { 
     if (this.up('form').getForm().isValid()) { 
      this.up('form').getForm().submit({ 
       url: 'Home/Upload', 
       waitMsg: 'Uploading your file...', 
       success: function (form, o) //(3) 
       { 
        Ext.Msg.show({ 
         title: 'Result', 
         msg: o.result.result, 
         buttons: Ext.Msg.OK, 
         icon: Ext.Msg.INFO 
        }); 
       }, 
       failure: function (form, o) //(4) 
       { 
        Ext.Msg.show({ 
         title: 'Result', 
         msg: o.result.error, 
         buttons: Ext.Msg.OK, 
         icon: Ext.Msg.ERROR 
        }); 
       } 
      }); 
     } 
    } 
}] 

誰もがこれを行う方法を知っていますか?ファイルであるパラメータを持つべきですか?

答えて

3

次のようなファイルを扱うことができます。

public void UploadFile(HttpRequestMessage request) 
{ 
    HttpContext context = HttpContext.Current; 
    HttpPostedFile postedFile = context.Request.Files["file"]; 
    // ... 
} 
+0

ありがとう...今は、Excelファイルの特定のタブを読む方法を理解するだけでいいです。 – solarissf

+0

@solarissf http://stackoverflow.com/questions/15828/reading-excel-files-from-c-sharp –

+0

コンテキスト.Request.Files [0] 'は、インデックスベースのアクセスにも同様に役立ちます。 – RBT

0

もう1つの可能な解決策を。 Web APIメソッドでは、ClosedXMLのnugetパッケージを使用して、次のコンテンツを含むストリームを読み込みます。

using ClosedXML.Excel; 

public async void UploadFile() 
{ 
    var context = HttpContext.Current; 

    if (!Request.Content.IsMimeMultipartContent()) 
    { 
     throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    } 

    var provider = new MultipartMemoryStreamProvider(); 
    await Request.Content.ReadAsMultipartAsync(provider); 

    foreach (HttpContent ctnt in provider.Contents) 
    { 
     //now read individual part into STREAM 
     var stream = await ctnt.ReadAsStreamAsync(); 
     if (stream.Length != 0) 
     { 
      //handle the stream here 
      using (XLWorkbook excelWorkbook = new XLWorkbook(stream)) 
      { 
       var name = excelWorkbook.Worksheet(1).Name; 
      } 
     } 
    } 
} 
関連する問題