NPOI export Excel file practical tutorial (Vue+C#)

1. Front-end

1、api

export function GetTestExcel(query) {
  return request({
    url: 'api/Test/GetTestExcel',
    method: 'get',
    responseType: 'blob',
    params: transformAbpListQuery(query)
  })
}

2. Call function

//点击导出按钮绑定exportData函数
exportData(listQuery = null) {
      //这里的listQuery是结合搜索框来的,没有业务需求的请忽略
      if (listQuery != null) {
        this.listQuery = listQuery;
      }
      this.loading = true;
      GetTestExcel(this.listQuery)
        .then((res) => {
          this.loading = false;
          const blob = new Blob([res], { type: "application/vnd.ms-excel" });
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(
              res,
              `测试明细_${moment().format("YYYYMMDDHHmmss")}.xls`
            );
          } else {
            const downloadElement = document.createElement("a");
            const href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = `测试明细_${moment().format(
              "YYYYMMDDHHmmss"
            )}.xls`; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放blob对象
          }
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },

2. Backend

1. Controller

/// <summary>
        /// 导出测试Excel
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTestExcel")]
        public async Task<IActionResult> GetTestExcel(PageQueryExcelFiterRequestDto input)
        {
            try
            {
                //这里取值要导出Excel的数据列表list
                //这里用到自定义NPOIHelper类里的ListToDataTable函数
                DataTable TestListTable= NPOIHelper.ListToDataTable(list);
                
                //这里用到自定义NPOIHelper类里的DataTableToExcel函数
                var ms = NPOIHelper.DataTableToExcel(TestListTable, "测试列表");

                return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "测试列表.xls");
            }
            catch (Exception ex)
            {
                var fileContents = System.Text.Encoding.UTF8.GetBytes(ex.Message);
                return File(fileContents, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "错误信息.xls");
                //也可以直接抛出异常 throw ex,看具体业务需求
            }
        }

2. NPOI category

public static DataTable ListToDataTable<T>(List<T> list)
        {
            //创建一个名为"tableName"的空表
            DataTable dt = new DataTable("tableName");

            //创建传入对象名称的列
            foreach (var item in list.FirstOrDefault().GetType().GetProperties())
            {
                dt.Columns.Add(item.Name);
            }
            //循环存储
            foreach (var item in list)
            {
                //新加行
                DataRow value = dt.NewRow();
                //根据DataTable中的值,进行对应的赋值
                foreach (DataColumn dtColumn in dt.Columns)
                {
                    int i = dt.Columns.IndexOf(dtColumn);
                    //基元元素,直接复制,对象类型等,进行序列化
                    if (value.GetType().IsPrimitive)
                    {
                        value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
                    }
                    else
                    {
                        value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));
                    }
                }
                dt.Rows.Add(value);
            }
            return dt;
        }
public static MemoryStream DataTableToExcel(DataTable table, string workbookname)
        {
            MemoryStream ms = new MemoryStream();
            IWorkbook workbook = new HSSFWorkbook();

            using (table)
            {
                ISheet sheet = workbook.CreateSheet("" + workbookname + "");
                sheet.DefaultColumnWidth = 1 * 15;
                sheet.DefaultRowHeight = 20;
                ICellStyle coluStyles = workbook.CreateCellStyle();
                coluStyles.Alignment = HorizontalAlignment.Center;
                coluStyles.VerticalAlignment = VerticalAlignment.Center;


                IRow headerRow = sheet.CreateRow(0);

                ICellStyle columStyles = workbook.CreateCellStyle();
                int k = 0;
                foreach (DataColumn column in table.Columns)
                {
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);

                    headerRow.GetCell(column.Ordinal).CellStyle = coluStyles;
                    headerRow.Height = 450;
                    if (column.MaxLength > 0)
                    {
                        try
                        {
                            sheet.SetColumnWidth(k, column.MaxLength * 30);
                        }
                        catch (Exception)
                        {

                        }
                       
                    }

                    k++;
                }

                int rowIndex = 1;
                Regex rex = new Regex(@"^[-]?\d+[.]?\d*$");
                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    foreach (DataColumn column in table.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        dataRow.GetCell(column.Ordinal).CellStyle = columStyles;
                        dataRow.Height = 380;

                        ICell newCell = dataRow.CreateCell(column.Ordinal);

                        string drValue = row[column].ToString();
                        #region 
                        if (column.ColumnName == "银行账号")
                        {
                            newCell.SetCellValue(drValue);
                            continue;
                        }
                        
                        #endregion
                        try
                        {
                            if (column.DataType == typeof(System.Decimal))
                            {
                                double doubV = 0;
                                double.TryParse(drValue, out doubV);
                                newCell.SetCellValue(doubV);
                            }
                            else
                            {
                                newCell.SetCellValue(drValue);
                            }
                        }
                        catch (Exception ex)
                        {

                            newCell.SetCellValue(ex.Message);
                            continue;
                        }

                    }

                    rowIndex++;
                }


            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            return ms;
        }

3. Acknowledgments

        Thank you all for your reading and support, and I wish you all a happy study!

Guess you like

Origin blog.csdn.net/Leewayah/article/details/131617331