mirror of https://github.com/nocodb/nocodb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
220 lines
7.9 KiB
220 lines
7.9 KiB
3 years ago
|
import XLSX from 'xlsx'
|
||
|
import { UITypes } from '~/components/project/spreadsheet/helpers/uiTypes'
|
||
3 years ago
|
import TemplateGenerator from '~/components/import/templateParsers/TemplateGenerator'
|
||
3 years ago
|
import { getCheckboxValue, isCheckboxType } from '~/components/import/templateParsers/parserHelpers'
|
||
3 years ago
|
|
||
|
const excelTypeToUidt = {
|
||
|
d: UITypes.DateTime,
|
||
|
b: UITypes.Checkbox,
|
||
|
n: UITypes.Number,
|
||
|
s: UITypes.SingleLineText
|
||
|
}
|
||
|
|
||
|
export default class ExcelTemplateAdapter extends TemplateGenerator {
|
||
3 years ago
|
constructor(name, ab, parserConfig = {}) {
|
||
3 years ago
|
super()
|
||
3 years ago
|
this.config = {
|
||
|
maxRowsToParse: 500,
|
||
|
...parserConfig
|
||
|
}
|
||
3 years ago
|
this.name = name
|
||
3 years ago
|
this.excelData = ab
|
||
3 years ago
|
this.project = {
|
||
|
title: this.name,
|
||
|
tables: []
|
||
|
}
|
||
|
this.data = {}
|
||
|
}
|
||
|
|
||
3 years ago
|
async init() {
|
||
2 years ago
|
const options = {
|
||
|
cellText: true,
|
||
|
cellDates: true
|
||
|
}
|
||
|
if (this.name.slice(-3) === 'csv') {
|
||
|
this.wb = XLSX.read(
|
||
|
(new TextDecoder).decode(new Uint8Array(this.excelData)),
|
||
|
{
|
||
|
type: "string",
|
||
|
...options
|
||
|
});
|
||
|
} else {
|
||
|
this.wb = XLSX.read(
|
||
|
new Uint8Array(this.excelData),
|
||
|
{
|
||
|
type: 'array',
|
||
|
...options
|
||
|
})
|
||
|
}
|
||
3 years ago
|
}
|
||
|
|
||
3 years ago
|
parse() {
|
||
3 years ago
|
const tableNamePrefixRef = {}
|
||
3 years ago
|
for (let i = 0; i < this.wb.SheetNames.length; i++) {
|
||
3 years ago
|
const columnNamePrefixRef = { id: 0 }
|
||
3 years ago
|
const sheet = this.wb.SheetNames[i]
|
||
2 years ago
|
let tn = (sheet || 'table').replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_').trim()
|
||
3 years ago
|
|
||
|
while (tn in tableNamePrefixRef) {
|
||
3 years ago
|
tn = `${tn}${++tableNamePrefixRef[tn]}`
|
||
|
}
|
||
3 years ago
|
tableNamePrefixRef[tn] = 0
|
||
3 years ago
|
|
||
3 years ago
|
const table = { table_name: tn, ref_table_name: tn, columns: [] }
|
||
3 years ago
|
this.data[tn] = []
|
||
3 years ago
|
const ws = this.wb.Sheets[sheet]
|
||
3 years ago
|
const range = XLSX.utils.decode_range(ws['!ref'])
|
||
3 years ago
|
const rows = XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false, cellDates: true, defval: null })
|
||
3 years ago
|
|
||
3 years ago
|
if (this.name.slice(-3) !== 'csv') {
|
||
|
// fix precision bug & timezone offset issues introduced by xlsx
|
||
|
const basedate = new Date(1899, 11, 30, 0, 0, 0)
|
||
|
// number of milliseconds since base date
|
||
|
const dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000
|
||
|
// number of milliseconds in a day
|
||
|
const day_ms = 24 * 60 * 60 * 1000
|
||
|
// handle date1904 property
|
||
|
const fixImportedDate = (date) => {
|
||
|
const parsed = XLSX.SSF.parse_date_code((date.getTime() - dnthresh) / day_ms, {
|
||
|
date1904: this.wb.Workbook.WBProps.date1904
|
||
|
})
|
||
|
return new Date(parsed.y, parsed.m, parsed.d, parsed.H, parsed.M, parsed.S)
|
||
|
}
|
||
|
// fix imported date
|
||
|
rows = rows.map(r => r.map((v) => {
|
||
|
return v instanceof Date ? fixImportedDate(v) : v
|
||
|
}))
|
||
3 years ago
|
}
|
||
3 years ago
|
|
||
3 years ago
|
const columnNameRowExist = +rows[0].every(v => v === null || typeof v === 'string')
|
||
3 years ago
|
|
||
|
// const colLen = Math.max()
|
||
3 years ago
|
for (let col = 0; col < rows[0].length; col++) {
|
||
3 years ago
|
let cn = ((columnNameRowExist && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||
|
||
2 years ago
|
`field_${col + 1}`).replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_').trim()
|
||
3 years ago
|
|
||
3 years ago
|
while (cn in columnNamePrefixRef) {
|
||
3 years ago
|
cn = `${cn}${++columnNamePrefixRef[cn]}`
|
||
|
}
|
||
3 years ago
|
columnNamePrefixRef[cn] = 0
|
||
|
|
||
3 years ago
|
const column = {
|
||
3 years ago
|
column_name: cn,
|
||
|
ref_column_name: cn
|
||
3 years ago
|
}
|
||
3 years ago
|
|
||
3 years ago
|
table.columns.push(column)
|
||
|
|
||
3 years ago
|
// const cellId = `${col.toString(26).split('').map(s => (parseInt(s, 26) + 10).toString(36).toUpperCase())}2`;
|
||
|
const cellId = XLSX.utils.encode_cell({
|
||
|
c: range.s.c + col,
|
||
3 years ago
|
r: columnNameRowExist
|
||
3 years ago
|
})
|
||
|
const cellProps = ws[cellId] || {}
|
||
3 years ago
|
column.uidt = excelTypeToUidt[cellProps.t] || UITypes.SingleLineText
|
||
|
|
||
|
// todo: optimize
|
||
|
if (column.uidt === UITypes.SingleLineText) {
|
||
|
// check for long text
|
||
3 years ago
|
if (rows.some(r =>
|
||
|
(r[col] || '').toString().match(/[\r\n]/) ||
|
||
|
(r[col] || '').toString().length > 255)
|
||
|
) {
|
||
3 years ago
|
column.uidt = UITypes.LongText
|
||
|
} else {
|
||
3 years ago
|
const vals = rows.slice(columnNameRowExist ? 1 : 0).map(r => r[col]).filter(v => v !== null && v !== undefined && v.toString().trim() !== '')
|
||
3 years ago
|
|
||
|
const checkboxType = isCheckboxType(vals)
|
||
|
if (checkboxType.length === 1) {
|
||
|
column.uidt = UITypes.Checkbox
|
||
3 years ago
|
} else {
|
||
3 years ago
|
// todo: optimize
|
||
3 years ago
|
// check column is multi or single select by comparing unique values
|
||
3 years ago
|
// todo:
|
||
3 years ago
|
if (vals.some(v => v && v.toString().includes(','))) {
|
||
3 years ago
|
let flattenedVals = vals.flatMap(v => v ? v.toString().trim().split(/\s*,\s*/) : [])
|
||
|
const uniqueVals = flattenedVals = flattenedVals
|
||
|
.filter((v, i, arr) => i === arr.findIndex(v1 => v.toLowerCase() === v1.toLowerCase()))
|
||
|
if (flattenedVals.length > uniqueVals.length && uniqueVals.length <= Math.ceil(flattenedVals.length / 2)) {
|
||
3 years ago
|
column.uidt = UITypes.MultiSelect
|
||
3 years ago
|
column.dtxp = `'${uniqueVals.join("','")}'`
|
||
3 years ago
|
}
|
||
|
} else {
|
||
3 years ago
|
const uniqueVals = vals.map(v => v.toString().trim()).filter((v, i, arr) => i === arr.findIndex(v1 => v.toLowerCase() === v1.toLowerCase()))
|
||
|
if (vals.length > uniqueVals.length && uniqueVals.length <= Math.ceil(vals.length / 2)) {
|
||
3 years ago
|
column.uidt = UITypes.SingleSelect
|
||
3 years ago
|
column.dtxp = `'${uniqueVals.join("','")}'`
|
||
3 years ago
|
}
|
||
3 years ago
|
}
|
||
|
}
|
||
|
}
|
||
3 years ago
|
} else if (column.uidt === UITypes.Number) {
|
||
3 years ago
|
if (rows.slice(1, this.config.maxRowsToParse).some((v) => {
|
||
3 years ago
|
return v && v[col] && parseInt(+v[col]) !== +v[col]
|
||
|
})) {
|
||
|
column.uidt = UITypes.Decimal
|
||
|
}
|
||
3 years ago
|
if (rows.slice(1, this.config.maxRowsToParse).every((v, i) => {
|
||
3 years ago
|
const cellId = XLSX.utils.encode_cell({
|
||
|
c: range.s.c + col,
|
||
3 years ago
|
r: i + (columnNameRowExist)
|
||
3 years ago
|
})
|
||
|
|
||
|
const cellObj = ws[cellId]
|
||
|
|
||
|
return !cellObj || (cellObj.w && cellObj.w.startsWith('$'))
|
||
|
})) {
|
||
|
column.uidt = UITypes.Currency
|
||
|
}
|
||
3 years ago
|
} else if (column.uidt === UITypes.DateTime) {
|
||
3 years ago
|
if (rows.slice(1, this.config.maxRowsToParse).every((v, i) => {
|
||
3 years ago
|
const cellId = XLSX.utils.encode_cell({
|
||
|
c: range.s.c + col,
|
||
3 years ago
|
r: i + columnNameRowExist
|
||
3 years ago
|
})
|
||
|
|
||
|
const cellObj = ws[cellId]
|
||
|
return !cellObj || (cellObj.w && cellObj.w.split(' ').length === 1)
|
||
|
})) {
|
||
|
column.uidt = UITypes.Date
|
||
|
}
|
||
3 years ago
|
}
|
||
|
}
|
||
|
|
||
3 years ago
|
let rowIndex = 0
|
||
3 years ago
|
for (const row of rows.slice(1)) {
|
||
|
const rowData = {}
|
||
|
for (let i = 0; i < table.columns.length; i++) {
|
||
3 years ago
|
if (table.columns[i].uidt === UITypes.Checkbox) {
|
||
3 years ago
|
rowData[table.columns[i].column_name] = getCheckboxValue(row[i])
|
||
3 years ago
|
} else if (table.columns[i].uidt === UITypes.Currency) {
|
||
|
const cellId = XLSX.utils.encode_cell({
|
||
|
c: range.s.c + i,
|
||
3 years ago
|
r: rowIndex + columnNameRowExist
|
||
3 years ago
|
})
|
||
|
|
||
|
const cellObj = ws[cellId]
|
||
3 years ago
|
rowData[table.columns[i].column_name] = (cellObj && cellObj.w && cellObj.w.replace(/[^\d.]+/g, '')) || row[i]
|
||
3 years ago
|
} else if (table.columns[i].uidt === UITypes.SingleSelect || table.columns[i].uidt === UITypes.MultiSelect) {
|
||
3 years ago
|
rowData[table.columns[i].column_name] = (row[i] || '').toString().trim() || null
|
||
3 years ago
|
} else {
|
||
|
// toto: do parsing if necessary based on type
|
||
3 years ago
|
rowData[table.columns[i].column_name] = row[i]
|
||
3 years ago
|
}
|
||
3 years ago
|
}
|
||
3 years ago
|
this.data[tn].push(rowData)
|
||
3 years ago
|
rowIndex++
|
||
3 years ago
|
}
|
||
|
this.project.tables.push(table)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
getTemplate() {
|
||
|
return this.project
|
||
|
}
|
||
|
|
||
|
getData() {
|
||
|
return this.data
|
||
|
}
|
||
|
}
|