将Excel文件上载到Web API

将Excel文件上载到Web API,excel,asp.net-web-api,extjs,Excel,Asp.net Web Api,Extjs,我正试图上传一个excel文件到我的WebApi,并处理它的内容。 我已经完成了extJs部分通过上传按钮发送文件。(代码如下) 我的问题是我不知道如何构建webApi部件来处理excel文件。我猜我必须有一个HttpPost 假WebApi: public string SampleUploadFile() { return _repo.UploadFile(); } xtype: 'form', //renderTo: 'fi-form', //(5) fileUpload: tr

我正试图上传一个excel文件到我的WebApi,并处理它的内容。 我已经完成了extJs部分通过上传按钮发送文件。(代码如下)

我的问题是我不知道如何构建webApi部件来处理excel文件。我猜我必须有一个HttpPost

假WebApi:

public string SampleUploadFile()
{
    return _repo.UploadFile();
}
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
                    });
                }
            });
        }
    }
}]
Extjs代码:

public string SampleUploadFile()
{
    return _repo.UploadFile();
}
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
                    });
                }
            });
        }
    }
}]

有人知道怎么做吗?我应该有一个文件参数吗?

您可以这样处理文件:

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

另一种可能的解决办法。web API方法使用nuget包读取包含excel内容的流:

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

我想与大家分享另一种使用ExcelDataReader.DataSet库实现WEB API的方法

        [Route("ReadFile")]
        [HttpPost]
        public string ReadFile()
        {
            try
            {
                #region Variable Declaration
                string message = "";
                HttpResponseMessage ResponseMessage = null;
                var httpRequest = HttpContext.Current.Request;
                DataSet dsexcelRecords = new DataSet();
                IExcelDataReader reader = null;
                HttpPostedFile Inputfile = null;
                Stream FileStream = null;
                #endregion
 
                #region Save Student Detail From Excel
                using (dbCodingvilaEntities objEntity = new dbCodingvilaEntities())
                {
                    if (httpRequest.Files.Count > 0)
                    {
                        Inputfile = httpRequest.Files[0];
                        FileStream = Inputfile.InputStream;
 
                        if (Inputfile != null && FileStream != null)
                        {
                            if (Inputfile.FileName.EndsWith(".xls"))
                                reader = ExcelReaderFactory.CreateBinaryReader(FileStream);
                            else if (Inputfile.FileName.EndsWith(".xlsx"))
                                reader = ExcelReaderFactory.CreateOpenXmlReader(FileStream);
                            else
                                message = "The file format is not supported.";
 
                            dsexcelRecords = reader.AsDataSet();
                            reader.Close();
 
                            if (dsexcelRecords != null && dsexcelRecords.Tables.Count > 0)
                            {
                                DataTable dtStudentRecords = dsexcelRecords.Tables[0];
                                for (int i = 0; i < dtStudentRecords.Rows.Count; i++)
                                {
                                    Student objStudent = new Student();
                                    objStudent.RollNo = Convert.ToInt32(dtStudentRecords.Rows[i][0]);
                                    objStudent.EnrollmentNo = Convert.ToString(dtStudentRecords.Rows[i][1]);
                                    objStudent.Name = Convert.ToString(dtStudentRecords.Rows[i][2]);
                                    objStudent.Branch = Convert.ToString(dtStudentRecords.Rows[i][3]);
                                    objStudent.University = Convert.ToString(dtStudentRecords.Rows[i][4]);
                                    objEntity.Students.Add(objStudent);
                                }
 
                                int output = objEntity.SaveChanges();
                                if (output > 0)
                                    message = "The Excel file has been successfully uploaded.";
                                else
                                    message = "Something Went Wrong!, The Excel file uploaded has fiald.";
                            }
                            else
                                message = "Selected file is empty.";
                        }
                        else
                            message = "Invalid File.";
                    }
                    else
                        ResponseMessage = Request.CreateResponse(HttpStatusCode.BadRequest);
                }
                return message;
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
[路由(“读取文件”)]
[HttpPost]
公共字符串读取文件()
{
尝试
{
#区域变量声明
字符串消息=”;
HttpResponseMessage ResponseMessage=null;
var httpRequest=HttpContext.Current.Request;
数据集dsexcelRecords=新数据集();
IExcelDataReader=null;
HttpPostedFile Inputfile=null;
Stream FileStream=null;
#端区
#区域从Excel保存学生详细信息
使用(dbcodingvilaenties objEntity=new dbcodingvilaenties())
{
如果(httpRequest.Files.Count>0)
{
Inputfile=httpRequest.Files[0];
FileStream=Inputfile.InputStream;
if(Inputfile!=null&&FileStream!=null)
{
if(Inputfile.FileName.EndsWith(“.xls”))
reader=ExcelReaderFactory.CreateBinaryReader(文件流);
else if(Inputfile.FileName.EndsWith(“.xlsx”))
reader=ExcelReaderFactory.CreateOpenXmlReader(文件流);
其他的
message=“不支持该文件格式。”;
dsexcelRecords=reader.AsDataSet();
reader.Close();
if(dsexcelRecords!=null&&dsexcelRecords.Tables.Count>0)
{
DataTable dtStudentRecords=dsexcelRecords.Tables[0];
对于(int i=0;i0)
message=“Excel文件已成功上载。”;
其他的
message=“出现问题!上载的Excel文件已失效。”;
}
其他的
message=“所选文件为空。”;
}
其他的
message=“无效文件。”;
}
其他的
ResponseMessage=Request.CreateResponse(HttpStatusCode.BadRequest);
}
返回消息;
#端区
}
捕获(例外)
{
投掷;
}
}

您可以阅读本手册,逐步了解详细的级别说明。

这很有效!谢谢现在我只需要弄清楚如何读取excel中的某个选项卡file@solarissf
context.Request.Files[0]
对基于索引的访问同样有用。