iT邦幫忙

0

exceljs 匯入與匯出的欄位寬度及行高不同

  • 分享至 

  • xImage

我使用vuejs 和 exceljs 開發一個元件,用來開啟及編輯xlsx檔案,
但現在碰到一個問題是,我來源的欄寬在陣列中顯示4.5,但我用excel 瀏覽來源檔案顯示3.88,匯出後的檔案顯示3.71;

而列高陣列中顯示undefined ,來源檔案excel 顯示16.5,匯出後的檔案顯示15。

這個問題困擾我好久了,我該如何修正呢?

<template>
  <el-dialog v-model="visible" title="編輯 Excel" width="80%">
    <input type="file" @change="handleFile" accept=".xlsx, .xls" />
    <el-button @click="saveExcel">儲存 Excel</el-button>
    <vue-office-excel :src="excelUrl" v-if="excelUrl" />
    <template #footer>
      <el-button @click="visible = false">關閉</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import ExcelJS from "exceljs";
import VueOfficeExcel from "@vue-office/excel";
import "@vue-office/excel/lib/index.css";

const props = defineProps({ modelValue: Boolean });
const emit = defineEmits(["update:modelValue"]);
const visible = ref(false);
const workbook = ref(null);
const excelUrl = ref("");

// Load Excel File
const handleFile = async (event) => {
  const file = event.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = async (e) => {
    const buffer = e.target.result;
    workbook.value = new ExcelJS.Workbook();
    await workbook.value.xlsx.load(buffer);


    const worksheet = workbook.value.worksheets[0];
    console.log("Readed:", worksheet.getRow(1).values);

    // Check Height and Width
    const columnWidths = worksheet.columns.map((col) => col.width);
    console.log("columnWidths:", columnWidths );
    const rowHeights= worksheet._rows.map((row) => row.height);
    console.log("rowHeights: ", rowHeights);

  };
  reader.readAsArrayBuffer(file);
};


const saveExcel = async () => {
  if (!workbook.value) return;
  const newFileName = "Edited_Quote.xlsx";
  const buffer = await workbook.value.xlsx.writeBuffer();
  const blob = new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });
  // download Excel file
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = newFileName;
  link.click();

  excelUrl.value = URL.createObjectURL(blob);
};


watch(() => props.modelValue, (val) => { visible.value = val; });
watch(visible, (val) => { emit("update:modelValue", val); });
</script>
圖片
  直播研討會

尚未有邦友回答

立即登入回答