WebApi使用EPPlus导出excel

Step1
当然是在Nuget下载EPPPlus,然后引入:

using OfficeOpenXml;

Step2直接上代码吧,使用EPPlus

private MemoryStream Export()
{
    List
list = new List
{ new Address { IPAddress = "127.0.0.1", Province = "XX", City = "XX" }, new Address { IPAddress = "127.0.0.2", Province = "XX", City = "XX" } }; using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("IP"); //First Line worksheet.Cells[1, 1].Value = "IP地址"; worksheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; worksheet.Cells[1, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; worksheet.Cells[1, 1].Style.Font.Bold = true; worksheet.Row(1).Height = 30; worksheet.Cells[1, 1, 1, 3].Merge = true; //Second Line worksheet.Cells[2, 1].Value = "—————————————————————————————————————————————————————————————"; worksheet.Cells[2, 1, 2, 3].Merge = true; //Third Line worksheet.Cells[3, 1].Value = "地址"; worksheet.Cells[3, 2].Value = "省份"; worksheet.Cells[3, 3].Value = "城市"; //other Line int num = 1; foreach (var item in list) { worksheet.Cells[num + 3, 1].Value = item.IPAddress.ToString(); worksheet.Cells[num + 3, 2].Value = item.Province; worksheet.Cells[num + 3, 3].Value = item.City; ++num; } //Format worksheet.Column(1).Width = 20; worksheet.Column(2).Width = 80; worksheet.Column(3).Width = 15; MemoryStream file = new MemoryStream(); package.SaveAs(file); file.Seek(0, SeekOrigin.Begin);//没这句话就格式错 return file; } }

然后是controller调用这个返回的MemoryStream

[HttpGet]
public HttpResponseMessage ExportList()
{
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(Export());
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//application/octet-stream
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = System.Web.HttpUtility.UrlEncode("file.xlsx");//file.xls用ContentType:application/vnd.ms-excel
    return response;
}

Step3直接浏览器输入地址
http://localhost:65084/api/EPPLUS/ExportList
就自动返回excel下载了。如果使用其他前端框架什么的得处理一下response


2017-8-15更新:
前两天发现大件事,上面这个可能用不了
直接地址啊什么的会自动下载。但是如果有token验证之类的,过不了api
提供另一种不太好的写法,使用base64,(vue前台的话是可以处理这个的)

public byte[] ExportSubjectiveAnswerList(string questionId)
{
    using (var conn = new SqlConnection(Settings.ConnectionString))
    {
        string sql = $@"SELECT T1.Ext
                            ,T1.SubmittedDate
                            ,T2.Name AS SubmittedBy
                        FROM Feedback AS T1
                        INNER JOIN [User] AS T2 ON T1.SubmittedBy=T2.Id
                        WHERE QuestionId=@questionId AND Answer='-'
                        ORDER BY SubmittedDate DESC";
        List result = conn.Query(sql, new { questionId }).ToList();

        string sql_question = @"SELECT Title FROM Question WHERE Id=@questionId";
        string title = conn.ExecuteScalar(sql_question, new { questionId });

        using (ExcelPackage package = new ExcelPackage())
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("主观题");
            //First Line
            worksheet.Cells[1, 1].Value = "调查问卷";
            worksheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
            worksheet.Cells[1, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
            worksheet.Cells[1, 1].Style.Font.Bold = true;
            worksheet.Row(1).Height = 30;
            worksheet.Cells[1, 1, 1, 3].Merge = true;
            //Second Line
            worksheet.Cells[2, 1].Value = title;
            worksheet.Cells[2, 1, 2, 3].Merge = true;
            //Third Line
            worksheet.Cells[3, 1].Value = "提交时间";
            worksheet.Cells[3, 2].Value = "建议";
            worksheet.Cells[3, 3].Value = "提交人";
            //other Line
            int num = 1;
            foreach (var item in result)
            {
                worksheet.Cells[num + 3, 1].Value = item.SubmittedDate.ToString();
                worksheet.Cells[num + 3, 2].Value = item.Ext;
                worksheet.Cells[num + 3, 3].Value = item.SubmittedBy;
                ++num;
            }
            //Format
            worksheet.Column(1).Width = 20;
            worksheet.Column(2).Width = 80;
            worksheet.Column(3).Width = 15;
            MemoryStream file = new MemoryStream();
            package.SaveAs(file);

            //转化为byte[]
            byte[] bytes = file.ToArray();
            file.Seek(0, SeekOrigin.Begin);//没这句话就格式错

            return bytes;
        }
    }
}
[HttpGet]
public ResponseMsg ExportSubjectiveAnswerList(string questionId)
{
    try
    {
        return ResponseMsg.Build(ResponseCode.Successed, "操作成功!", Convert.ToBase64String(_management.ExportSubjectiveAnswerList(questionId)));
    }
    catch (Exception ex)
    {
        return ResponseMsg.Build(ResponseCode.ValidationFailure, ex.Message, null);
    }
}

前端Vue代码片段:

export11(){
    this.$http.get(this.apiUrl.exportOptionTypeAnswerStatistics).then((res) => {
        this.filedownload(res.data.Body,'option.xlsx');
    })
}

你可能感兴趣的:(WebApi使用EPPlus导出excel)