BT San Technology

19 November 2026

Importing Excel and CSV into a web app: checking data before saving and reporting errors

24 min read · Websites and web apps

Illustration: a monitor showing spreadsheet file icons, an import arrow and a validation list with green checks and orange warnings, beside document trays
AI-generated illustration

An accountant sends a customer list of 800 rows to be imported. The system imports 412 rows and stops at row 413 because a date is in the wrong format. Nobody knows which rows went in and which did not. Fix the file and upload it again, and the same 412 customers appear twice. In another case, the phone number 0812345678 becomes 812345678 because Excel dropped the leading zero and nobody noticed. Both problems have the same fix: check the whole file first without writing anything (a dry run), then write everything or write nothing.

This article builds a CSV importer in TypeScript that Node 24 runs directly, using node:sqlite, which ships with Node, as the sample database. There is nothing to install. A manager can follow the explanations and tables, and an engineer can run the code.

The real problem: a file from Excel is not the data the system expects

A CSV looks like a plain text file, but a file saved from Excel hides several layers of small problems. Consider three hypothetical situations. They are not from any BT San customer project.

  • A wholesaler moves its customer list from Excel to a new system: customer code 00101 was opened and saved as 101, so the code no longer matches the original invoices, and the leading 0 of a phone number is gone.
  • A small factory imports stock from a warehouse department file: the amount 1,200.50 is inside quotation marks, but some rows contain 5,000 without them. The reader splits it into two fields, and the rest of the row shifts into the wrong columns.
  • A service company imports customer contracts: the contract start date is typed 21/11/2569. Some rows use the Buddhist Era (B.E.) year and some use the Gregorian (C.E.) year, and one row has 31/02/2569, which does not exist. If the system guesses, it produces a wrong date with no warning.

The example in this article deliberately includes all of these bad rows in the file customers-bad.csv. Every row of data is fictional.

Facts from the documentation: what CSV and Excel actually agree on

TopicWhat the documentation saysEffect on our code
Quotation marksRFC 4180 says a field that contains a line break, a quotation mark or a comma should be enclosed in quotation marks, and a quotation mark inside the field must be written twice.The reader must walk the file character by character and remember whether it is inside quotation marks. split(",") does not work.
Line endings and field countRFC 4180 says each record is separated by CRLF and every line should have the same number of fields (this RFC is an Informational document and uses the word "should").Accept both CRLF and LF, then check the column count on every row.
Leading zerosMicrosoft documentation says Excel uses the default data format settings to interpret each column when it opens a file, and recommends the Text Import Wizard to convert columns with leading zeros to text.Never guess that a code is a number. Check the code against its stated format, for example exactly 5 digits.
Server-side validationOWASP recommends checking both syntax (type and format) and semantics (whether the value makes sense for the business), defining what is accepted and rejecting the rest, and validating on the server even if the browser already validated.All rules live in a testable server-side function.
File size and typeOWASP File Upload recommends setting a maximum size for uploaded files to protect storage, and allowing only the extensions the business needs.Limit the size and extension before reading the contents.
transactionSQLite explains that changes happen inside a transaction that ends with COMMIT or ROLLBACK, and recommends issuing ROLLBACK yourself when an error occurs so that the state after an error is always the same.Wrap the whole batch of writes in BEGIN ... COMMIT, and ROLLBACK in the catch block.
Summary of RFC 4180, the OWASP Input Validation and File Upload Cheat Sheets, Microsoft documentation on importing text/CSV files, and SQLite documentation on transactions, as read on 2026-11-21. Other databases differ in detail, so read the documentation for the one you use.

In the Node v24 documentation, node:sqlite is marked Stability 1.2 (release candidate), not yet fully stable. On the test machine (Node 24.21.0) there was no ExperimentalWarning, but other versions may show one. It is used in the example so the code runs without installing anything. A real system uses the PostgreSQL or MySQL your team already runs, with the same structure.

Overview of the example

It is split into three layers so that each can be tested on its own: the file reader (csv.ts), the per-row validation rules (rules.ts), which are pure functions that never touch the database, and the layer that connects the two to the database (dryrun.ts, importer.ts). The folder examples/excel-csv-import-validation-dry-run/ needs Node 24 or later. There is no npm install and no network access.

FilePurpose
csv.tsCSV reader: strips the BOM, handles CRLF, and handles commas and line breaks inside quotation marks
rules.tsMatches Thai/English column headers and holds the per-field validation rules
dryrun.tsChecks the whole file without writing, and produces a per-line report including duplicate rows
importer.tsImports in a single transaction and blocks re-importing the same file by hash
demo.tsRuns 5 scenarios and prints the results
customers-good.csv / customers-bad.csvSample files in UTF-8 with a BOM and CRLF. The second one contains several kinds of bad rows.
import.test.tsA node:test suite with 5 cases
output.txtOutput from the real run on 2026-11-21

Step 1: read the file correctly: BOM, CRLF and quotation marks

When Excel saves a CSV as UTF-8, it puts a BOM (the character U+FEFF) at the start of the file. If you do not strip it, the first column name carries an invisible character, and header matching fails with no error message. The reader below is a small state machine that remembers whether it is currently inside quotation marks, so it can read the name ร้านสุขใจ, สาขา 2 ("Suk Jai Shop, Branch 2") as a single field.

csv.ts
// อ่าน CSV ตาม RFC 4180 แบบเล็กที่สุด: ตัด BOM, รองรับ CRLF/LF, ฟิลด์ในเครื่องหมายคำพูด (มี comma, ขึ้นบรรทัดใหม่, "" แทน ")
export function parseCsv(text: string): string[][] {
  if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // BOM ที่ Excel ใส่ตอนบันทึกเป็น UTF-8
  const rows: string[][] = [];
  let row: string[] = [];
  let field = "";
  let quoted = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (quoted) {
      if (c === '"' && text[i + 1] === '"') { field += '"'; i++; }
      else if (c === '"') quoted = false;
      else field += c;
    } else if (c === '"') quoted = true;
    else if (c === ",") { row.push(field); field = ""; }
    else if (c === "\n" || c === "\r") {
      if (c === "\r" && text[i + 1] === "\n") i++;
      row.push(field); field = "";
      rows.push(row); row = [];
    } else field += c;
  }
  if (quoted) throw new Error("เครื่องหมายคำพูดเปิดแล้วไม่ปิด: ไฟล์ถูกตัดหรือเสียหาย");
  if (field !== "" || row.length) { row.push(field); rows.push(row); }
  return rows.filter((r) => r.some((x) => x.trim() !== "")); // ทิ้งบรรทัดว่างท้ายไฟล์
}
csv.ts drops trailing blank lines and throws an error if a quotation mark is not closed

Step 2: per-field rules that do not guess for the user

Every rule is a pure function that takes a value and returns either a value or a list of errors. That makes the rules easy to test and reusable in both the dry run and the real import. The principle is not to fix wrong values silently, except for format changes that do not alter the meaning, such as removing dashes from a phone number and removing commas from an amount. A code that lost its leading zeros is not repaired, because 101 may genuinely be a different code. It is reported, and the file owner fixes it.

rules.ts · lines 32–47
export function validateRow(get: (k: keyof Customer) => string): { value?: Customer; errors: CellError[] } {
  const errors: CellError[] = [];
  const bad = (column: string, message: string) => errors.push({ column, message });
  const code = get("code").trim();
  if (!/^\d{5}$/.test(code)) bad("รหัสลูกค้า", `ต้องเป็นตัวเลข 5 หลัก (ได้ "${code}") ศูนย์นำหน้าต้องไม่หาย`);
  const name = get("name").trim();
  if (!name) bad("ชื่อ", "ห้ามว่าง");
  const phone = get("phone").replace(/[\s-]/g, "");
  if (!/^0\d{8,9}$/.test(phone)) bad("โทรศัพท์", `ต้องขึ้นต้น 0 และยาว 9-10 หลัก (ได้ "${phone}")`);
  const creditText = get("credit").trim().replace(/,/g, ""); // 1,200.50 -> 1200.50
  const credit = /^\d+(\.\d{1,2})?$/.test(creditText) ? Number(creditText) : NaN;
  if (Number.isNaN(credit)) bad("วงเงินเครดิต", `ต้องเป็นจำนวนเงินไม่ติดลบ (ได้ "${get("credit")}")`);
  const since = parseDate(get("since").trim());
  if (!since) bad("วันที่เริ่ม", `วันที่ไม่ถูกต้อง (ได้ "${get("since")}") ใช้ วว/ดด/ปปปป หรือ ปปปป-ดด-วว`);
  return errors.length ? { errors } : { value: { code, name, phone, credit, since: since! }, errors };
}
rules.ts, function validateRow: checks every field and collects the errors instead of stopping at the first one

Note that the errors from every field in a row are collected together instead of stopping at the first one, so the person fixing the file can correct everything in one pass. Dates are specific to Thailand: a year greater than 2400 is treated as a Buddhist Era year and 543 is subtracted. Then the date is rebuilt and checked to see whether the day, month and year are unchanged. This catches 31/02/2569, which JavaScript would silently roll over to March if it were not checked.

rules.ts · lines 20–30
// 21/11/2569 (พ.ศ.) หรือ 2026-11-21 (ค.ศ.) -> "2026-11-21" ปีเกิน 2400 ถือเป็น พ.ศ. ลบ 543
export function parseDate(s: string): string | null {
  const m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(s) ?? /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
  if (!m) return null;
  const iso = s.includes("-");
  let [d, mo, y] = iso ? [+m[3], +m[2], +m[1]] : [+m[1], +m[2], +m[3]];
  if (y > 2400) y -= 543;
  const t = new Date(Date.UTC(y, mo - 1, d));
  if (t.getUTCFullYear() !== y || t.getUTCMonth() !== mo - 1 || t.getUTCDate() !== d) return null; // 31/02 ไม่มีจริง
  return t.toISOString().slice(0, 10);
}
rules.ts, parseDate: accepts dd/mm/yyyy in B.E. or C.E., and yyyy-mm-dd

The rule that a year > 2400 is a Buddhist Era year is a convention of this example. It works for current data, but if your file contains very old years or two-digit years, agree with the data owner first on how to read them.

Step 3: dry run: check the whole file and write nothing

A dry run walks the whole file through the same rules as the real import but does not write to the database. The database is only read, to see which codes already exist. The result is a per-line report. Line numbers match what the user sees in Excel (the header is line 1), so they can open the file and go straight to the problem. The column count of each row is checked before anything else, because an unquoted 5,000 shifts the values, and checking field by field after that would produce confusing, wrong messages.

dryrun.ts · lines 9–33
export function dryRun(text: string, existing: Set<string>): DryRun {
  const table = parseCsv(text);
  const head = mapHeader(table[0] ?? []);
  if (head.missing.length) return { fatal: `ขาดคอลัมน์: ${head.missing.join(", ")}`, valid: [], rows: [] };
  const seen = new Map<string, number>(); // รหัส -> เลขบรรทัดแรกที่เจอ
  const out: DryRun = { fatal: null, valid: [], rows: [] };
  table.slice(1).forEach((cells, i) => {
    const line = i + 2; // บรรทัดที่ผู้ใช้เห็นใน Excel (หัวตารางคือบรรทัด 1)
    if (cells.length !== table[0].length) { // เช่น 5,000 ไม่ใส่เครื่องหมายคำพูด -> แตกเป็นสองคอลัมน์ ค่าที่เหลือเลื่อนผิดช่อง
      out.rows.push({ line, code: (cells[0] ?? "").trim(), status: "error", errors: [{ column: "(ทั้งแถว)", message: `มี ${cells.length} คอลัมน์ แต่หัวตารางมี ${table[0].length} (มี comma ในค่าที่ไม่ได้ครอบด้วย " ?)` }] });
      return;
    }
    const r = validateRow((k) => cells[head.index.get(k)!] ?? "");
    const code = r.value?.code ?? (cells[head.index.get("code")!] ?? "").trim();
    if (r.value) {
      if (seen.has(code)) r.errors.push({ column: "รหัสลูกค้า", message: `ซ้ำกับบรรทัด ${seen.get(code)} ในไฟล์เดียวกัน` });
      else if (existing.has(code)) r.errors.push({ column: "รหัสลูกค้า", message: "มีในระบบแล้ว (ไม่เขียนทับ)" });
    }
    if (code && !seen.has(code)) seen.set(code, line);
    const ok = r.errors.length === 0;
    if (ok) out.valid.push(r.value!);
    out.rows.push({ line, code, status: ok ? "ok" : "error", errors: r.errors });
  });
  return out;
}
dryrun.ts checks the column count and the per-field rules, then checks for duplicates within the file and against the database

Step 4: import all or nothing, and make re-runs safe

The policy in this example is that if even one row is bad, the whole file is rejected, because it is easier for the user to fix the file and upload it again than to work out which rows already went in (other options are in the section on adapting to your business). When everything passes, a transaction starts, writes every row, and stores the file's SHA-256 hash in the same database. If someone uploads the same file again, the result is already_imported and no duplicate customers are created. If the dry run passes but someone adds the same code in the meantime, the write hits the PRIMARY KEY, and ROLLBACK leaves no half-written rows. The example includes a beforeWrite hook as an insertion point so the tests can simulate this situation.

importer.ts · lines 19–38
// all-or-nothing: ตรวจก่อน ถ้ามีแถวเสียแม้แถวเดียวไม่เขียนอะไรเลย ผ่านหมดค่อยเขียนใน transaction เดียว
export function importFile(db: DatabaseSync, text: string, beforeWrite?: () => void): Result {
  const hash = createHash("sha256").update(text).digest("hex").slice(0, 16);
  const done = db.prepare("SELECT rows FROM import_batches WHERE hash = ?").get(hash) as { rows: number } | undefined;
  if (done) return { status: "already_imported", inserted: 0, report: { fatal: null, valid: [], rows: [] } };
  const report = dryRun(text, existingCodes(db));
  if (report.fatal || report.rows.some((r) => r.status === "error")) return { status: "rejected", inserted: 0, report };
  beforeWrite?.(); // จุดแทรกสำหรับทดสอบ: จำลองคนอื่นเขียนระหว่าง dry run กับ transaction
  const ins = db.prepare("INSERT INTO customers VALUES (?, ?, ?, ?, ?, ?)");
  db.exec("BEGIN");
  try {
    for (const c of report.valid) ins.run(c.code, c.name, c.phone, Math.round(c.credit * 100), c.since, hash);
    db.prepare("INSERT INTO import_batches VALUES (?, ?)").run(hash, report.valid.length);
    db.exec("COMMIT");
  } catch (e) {
    db.exec("ROLLBACK"); // เช่นมีคนอื่นเพิ่มรหัสเดียวกันระหว่างทาง: PRIMARY KEY ชน -> ไม่มีแถวค้าง
    throw e;
  }
  return { status: "imported", inserted: report.valid.length, report };
}
importer.ts, function importFile: hashes the file, runs the dry run, then writes in a single transaction

Amounts are stored in satang (integers), not as decimals, so floating-point arithmetic cannot introduce errors.

A real run: five scenarios

demo.ts creates an in-memory database, inserts one customer with code 00001 first, and then runs five scenarios.

output.txt
1) dry run ไฟล์ที่มีแถวเสีย (ยังไม่เขียนอะไร)
  บรรทัด 2 [00101] error
    - โทรศัพท์: ต้องขึ้นต้น 0 และยาว 9-10 หลัก (ได้ "812345678")
  บรรทัด 3 [102] error
    - (ทั้งแถว): มี 6 คอลัมน์ แต่หัวตารางมี 5 (มี comma ในค่าที่ไม่ได้ครอบด้วย " ?)
  บรรทัด 4 [00103] error
    - ชื่อ: ห้ามว่าง
    - วงเงินเครดิต: ต้องเป็นจำนวนเงินไม่ติดลบ (ได้ "-500")
    - วันที่เริ่ม: วันที่ไม่ถูกต้อง (ได้ "31/02/2569") ใช้ วว/ดด/ปปปป หรือ ปปปป-ดด-วว
  บรรทัด 5 [00104] ok
  บรรทัด 6 [00104] error
    - รหัสลูกค้า: ซ้ำกับบรรทัด 5 ในไฟล์เดียวกัน
  บรรทัด 7 [00001] error
    - รหัสลูกค้า: มีในระบบแล้ว (ไม่เขียนทับ)
  บรรทัด 8 [00105] error
    - วันที่เริ่ม: วันที่ไม่ถูกต้อง (ได้ "ยังไม่กำหนด") ใช้ วว/ดด/ปปปป หรือ ปปปป-ดด-วว
  ผ่าน 1 / 7 แถว, ลูกค้าใน DB = 1
2) นำเข้าไฟล์เสีย -> ต้องถูกปฏิเสธทั้งไฟล์
  rejected inserted=0 ลูกค้าใน DB = 1
3) นำเข้าไฟล์ถูกต้อง (BOM + CRLF + comma ในเครื่องหมายคำพูด + พ.ศ.)
  imported inserted=3 ลูกค้าใน DB = 4
   {"code":"00101","name":"บริษัท สยามพืชผล จำกัด","phone":"0812345678","credit_satang":1200050,"since":"2026-11-21"}
   {"code":"00102","name":"ร้านสุขใจ, สาขา 2","phone":"0891112222","credit_satang":500000,"since":"2026-11-01"}
   {"code":"00103","name":"ห้างหุ้นส่วน \"มั่นคง\"","phone":"029998888","credit_satang":0,"since":"2025-01-01"}
4) รันไฟล์เดิมซ้ำ -> ต้องไม่เพิ่มแถว
  already_imported inserted=0 ลูกค้าใน DB = 4
5) ไฟล์ที่ผ่าน dry run แต่ชนกันตอนเขียนจริง -> rollback ทั้งชุด
  dry run ผ่าน 2/2
  import ล้ม: UNIQUE constraint failed: customers.code
  00201 อยู่ใน DB หรือไม่ = ไม่ (rollback แล้ว)
Output from the real run on 2026-11-21 with node demo.ts (Node 24.21.0), without --no-warnings

Reading the results one by one

  1. The dry run of the bad file with 7 rows passes only one row: line 2 has a phone number with a missing zero. Line 3 has 6 columns instead of 5 (5,000 without quotation marks). Line 4 has three wrong fields at once. Line 6 duplicates line 5 within the file. Line 7 duplicates a row already in the database. Line 8 has a date written as text. The customer count in the database is still 1.
  2. A real import of the bad file returns rejected and inserted=0. The database does not change, even though line 5 passed validation, because it is not written.
  3. The valid file, with a BOM, CRLF, names containing commas and quotation marks, imports correctly. The date 21/11/2569 becomes 2026-11-21, the amount 12,000.50 is stored as 1200050 satang, and the phone numbers keep their leading 0.
  4. Running the same file again returns already_imported, and the customer count stays at 4.
  5. The dry run passes 2/2, but in the meantime someone adds code 00202. The write collides and raises UNIQUE constraint failed, and then ROLLBACK runs. Code 00201, which was written just before, does not stay in the database.

Test suite

import.test.ts has 5 cases. Running node --test import.test.ts gives 5 passes. They cover the CSV reader (BOM, CRLF, commas and line breaks inside quotation marks, an unclosed quotation mark), dates (B.E./C.E.; the leap day 29/02/2567 passes but 29/02/2568 fails), the per-field rules (leading zeros, amounts with commas), the dry run (duplicates in the file, duplicates against the database, a wrong column count, line numbers that match Excel), and the import (rejecting the whole file, re-running, rollback). An in-memory database keeps the tests fast and leaves no files behind.

Real systems: databases, large files and encodings

  • Real database: replace node:sqlite with the PostgreSQL or MySQL driver. The structure stays the same: a unique key on the code, an import batch table and a single transaction. In PostgreSQL, use INSERT ... ON CONFLICT so that a collision becomes a result you can handle, not an error.
  • Large files: the example reads the whole file into memory, which is fine for files up to tens of thousands of rows. For anything larger, read as a stream, validate in batches, and write the validation results to a staging table first, then move them into the real table in a single transaction.
  • File size and type: limit the size and extension before reading the contents, as OWASP File Upload recommends, and limit the number of rows reported back so that a million-row file does not produce a million-line report.
  • Encoding: files from older Thai versions of Excel may be Windows-874, not UTF-8. If decoding as UTF-8 produces replacement characters (U+FFFD), reject the file and tell the user to save it as CSV UTF-8. This example does not implement that check.
  • The .xlsx format: do not read it directly without a vetted library. Ask the user to save it as CSV, or use an .xlsx reading library your team has evaluated.
  • Exporting back: if the system sends CSV files for people to open in Excel, values that start with = + - or @ can be interpreted as formulas (CSV injection). This must be handled at export time, as OWASP describes. It is outside this example.

Hypothetical examples: adapting it to three businesses

  • A retailer importing products and prices: keep the all-or-nothing policy. Add a rule that the selling price must not be lower than the cost, and always store barcodes as text.
  • An HR department importing hundreds of new employees at a time: it may choose to import only the rows that pass and send the failed rows back to be fixed. The caution is that you must record the import batch ID and the line number of each row, so that a second import does not create duplicates and the changes can be reversed. National ID data must also have restricted access and must not be printed to logs.
  • A sales team importing customers into a CRM: change from rejecting duplicate codes to updating the existing row (upsert). The dry run should show which rows will be created, which will be updated and which fields will change, and a person should confirm before it runs.

Common mistakes and a checklist

  • Reading CSV with split(","), so a name containing a comma breaks into two fields.
  • Not stripping the BOM, so the first column header is never matched.
  • Converting codes or phone numbers to numbers, so the leading zeros are lost permanently.
  • Letting JavaScript construct dates without checking them back, so 31/02 becomes 3 March.
  • Importing row by row with no transaction and stopping halfway, leaving half a batch that nobody can identify.
  • An error report that only says "invalid file" and does not give the line and column, so the user has to guess.
  • Not recording which files were already imported, so a second upload creates duplicate data.
  • Validating only in the browser, with no server-side check.
  1. Define a file template with an example, and tell users to save as CSV UTF-8.
  2. Limit the file size and extension before reading the contents.
  3. Read with a reader that handles BOM, CRLF and quotation marks.
  4. Check the column count, code format, dates and amounts on every row, and collect the errors from every field.
  5. Check for duplicate rows both within the file and against the database.
  6. Show the user a per-line, per-column report before they confirm.
  7. Import in a single transaction and ROLLBACK on error.
  8. Record the import batch ID and the file hash, so re-runs are safe and changes can be reversed.
  9. Test with files that are broken in several ways, not only with a valid file.

Caution: this example is for learning and is not production code. All rows of data are fictional. The validation rules (5-digit codes, 9-10 digit phone numbers, the Buddhist Era year threshold) are conventions of this example. A real business must define the rules together with the data owner. It was not tested with large files, with encodings other than UTF-8, with .xlsx files, or with concurrent use of a real database. If the data contains personal data, also consider the PDPA, access rights and how long uploaded files are kept.

References

  1. OWASP — Input Validation Cheat Sheet (accessed 2026-11-21)
  2. OWASP — File Upload Cheat Sheet (accessed 2026-11-21)
  3. OWASP — CSV Injection (accessed 2026-11-21)
  4. SQLite — Transaction (accessed 2026-11-21)
  5. Node.js v24 — SQLite (node:sqlite) (accessed 2026-11-21)
  6. Microsoft — Import or export text (.txt or .csv) files (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer