57 lines
2.3 KiB
JavaScript
57 lines
2.3 KiB
JavaScript
const XLSX = require('xlsx');
|
|
|
|
// อ่านไฟล์ Excel
|
|
const excel = XLSX.readFile('input.xlsx');
|
|
const sheet = excel.Sheets[excel.SheetNames[0]];
|
|
const data = XLSX.utils.sheet_to_json(sheet);
|
|
|
|
// รวมยอดงบประมาณตาม "แหล่งงบประมาณ"
|
|
const summary = {};
|
|
|
|
// ฟังก์ชันลบตัวเลขและจุดนำหน้า เช่น "33.เงินรายได้" → "เงินรายได้"
|
|
const cleanSource = (text) => {
|
|
if (!text) return '';
|
|
return text.toString().replace(/^\d+\.\s*/, '').trim();
|
|
};
|
|
|
|
// รวมงบประมาณ
|
|
data.forEach(row => {
|
|
const rawSource = row['แหล่งงบประมาณ']; // ชื่อคอลัมน์ใน Excel
|
|
const source = cleanSource(rawSource);
|
|
const budget = Number(row['งบประมาณ']) || 0;
|
|
|
|
if (!source) return; // ข้ามแถวที่ไม่มีแหล่งงบประมาณ
|
|
if (!summary[source]) summary[source] = 0;
|
|
|
|
summary[source] += budget;
|
|
});
|
|
|
|
// รวมยอดทั้งหมด
|
|
let grandTotal = 0;
|
|
Object.values(summary).forEach(total => (grandTotal += total));
|
|
|
|
// ฟังก์ชัน format ตัวเลขแบบมี comma + ทศนิยม 2 ตำแหน่ง
|
|
const formatNumber = (num) => {
|
|
return num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
};
|
|
|
|
// แปลงกลับเป็น array สำหรับ export
|
|
const result = Object.entries(summary).map(([source, total]) => ({
|
|
'แหล่งงบประมาณ': source,
|
|
'รวมงบประมาณ': formatNumber(total)
|
|
}));
|
|
|
|
// เพิ่มแถวสุดท้าย “รวมทั้งหมด”
|
|
result.push({
|
|
'แหล่งงบประมาณ': 'รวมทั้งหมด',
|
|
'รวมงบประมาณ': formatNumber(grandTotal)
|
|
});
|
|
|
|
// เขียนเป็นไฟล์ Excel ใหม่
|
|
const newSheet = XLSX.utils.json_to_sheet(result);
|
|
const newBook = XLSX.utils.book_new();
|
|
XLSX.utils.book_append_sheet(newBook, newSheet, 'Summary');
|
|
XLSX.writeFile(newBook, 'output.xlsx');
|
|
|
|
console.log('✅ สรุปตามแหล่งงบประมาณเสร็จแล้ว → output.xlsx');
|