xlsx.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // import * as XLSX from "xlsx";
  2. import * as XLSX from "xlsx-with-styles";
  3. export const get_excel_to_json = (file: any) => {
  4. return new Promise((resove) => {
  5. const reader = new FileReader();
  6. reader.readAsBinaryString(file);
  7. reader.onload = function (e: any) {
  8. const wb = XLSX.read(e.target.result, { type: "binary", cellStyles: true });
  9. const json = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
  10. resove(json);
  11. };
  12. });
  13. };
  14. export const export_json_to_excel = ({
  15. header = {},
  16. list = [],
  17. sheetName = 'sheetName',
  18. fileName = 'filename',
  19. autoWidth = true,
  20. }) => {
  21. const book = XLSX.utils.book_new();
  22. let sheetItem = XLSX.utils.json_to_sheet([header, ...list], {
  23. // header: Object.keys(header),
  24. cellDates: true,
  25. skipHeader: true,
  26. });
  27. // const style = {
  28. // fill: {
  29. // fgColor: { rgb: "FF9bc2e6" },
  30. // bgColor: { rgb: "FF9bc2e6" },
  31. // },
  32. // }
  33. // const range = sheetItem['!ref']
  34. // const start = '1'
  35. // const end = range?.split(':')[1].slice(1)
  36. // Object.keys(sheetItem).forEach(key => {
  37. // if ((key.length === 2 && key.endsWith(start)) || key.endsWith(end!)) {
  38. // sheetItem[key].s = style
  39. // }
  40. // })
  41. autoWidth && auto_width(sheetItem, json_to_array(Object.keys(header), list));
  42. XLSX.utils.book_append_sheet(book, sheetItem, sheetName);
  43. XLSX.writeFile(book, fileName + ".xlsx");
  44. };
  45. const auto_width = (sheetItem: any, data: any[]) => {
  46. const maxWidth = 50;
  47. /*set worksheet max width per col*/
  48. const colWidth = data.map((row: string[]) =>
  49. row.map((val) => {
  50. let width = 0;
  51. /*if null/undefined*/
  52. if (val !== null && val !== undefined) {
  53. if (val.toString().charCodeAt(0) > 255) {
  54. width = val.toString().length * 2;
  55. } else {
  56. width = val.toString().length;
  57. }
  58. } else {
  59. width = 10;
  60. }
  61. return {
  62. wch: width > maxWidth ? maxWidth : width,
  63. };
  64. })
  65. );
  66. /*start in the first row*/
  67. const result = colWidth[0];
  68. for (let i = 1; i < colWidth.length; i++) {
  69. for (let j = 0; j < colWidth[i].length; j++) {
  70. if (result[j].wch < colWidth[i][j].wch) {
  71. result[j].wch = colWidth[i][j].wch;
  72. }
  73. }
  74. }
  75. sheetItem["!cols"] = result;
  76. };
  77. const json_to_array = (key: string[], jsonData: any[]) => {
  78. const data = jsonData.map((v) => key.map((j) => v[j] + "站位"));
  79. return data;
  80. };