在使用 Vue.js 结合 Ant Design Vue (antdv) 开发时,要实现从后端 Java 接口获取数据并导出到表格的功能,你可以按照以下步骤进行:

1. 安装依赖

确保你已经安装了 axiosxlsxaxios 用于 HTTP 请求,而 xlsx 用于处理 Excel 文件。

npm install axios xlsx
  • 1.

2. 创建表格组件

创建一个 Vue 组件来展示表格,并且添加导出功能。

<template>
  <a-table :data-source="dataSource" size="middle">
    <!-- 列配置 -->
    <a-table-column v-for="(col, index) in columns" :key="index" :title="col.title" :dataIndex="col.dataIndex" />
    
    <!-- 导出按钮 -->
    <template #action>
      <a-button type="primary" @click="exportData">导出</a-button>
    </template>
  </a-table>
</template>

<script>
import axios from 'axios';
import XLSX from 'xlsx';

export default {
  data() {
    return {
      dataSource: [],
      columns: [
        { title: 'ID', dataIndex: 'id' },
        { title: '姓名', dataIndex: 'name' },
        // 更多列...
      ],
    };
  },
  methods: {
    fetchData() {
      axios.get('/api/data') // 替换为你的 Java 接口地址
        .then(response => {
          this.dataSource = response.data;
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    },
    exportData() {
      const ws = XLSX.utils.json_to_sheet(this.dataSource);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      
      // 将工作簿转换为二进制数据
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      // 创建 Blob 对象
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      
      // 创建下载链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'data.xlsx';
      link.click();
    },
    s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
      return buf;
    },
  },
  mounted() {
    this.fetchData();
  },
};
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.

注意事项:

  • 确保 /api/data 是你的后端 Java 接口的正确路径,该接口应返回 JSON 格式的数组数据。
  • 在导出功能中,XLSX.utils.json_to_sheet 方法将数据源转换为一个工作表,然后使用 XLSX.write 方法生成一个 Excel 文件。
  • s2ab 函数用于将字符串转换为 ArrayBuffer,这是 XLSX.write 方法要求的输出格式之一。

这样设置后,你的 Vue 应用程序就能从 Java 后端获取数据并在表格中显示,并提供一个导出按钮来下载这些数据为 Excel 文件。