forked from sheetjs/docs.sheetjs.com
2.9 KiB
2.9 KiB
sidebar_position | title |
---|---|
9 | Databases |
import current from '/version.js'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';
SQLite
Most platforms offer a simple way to query .sqlite
databases.
The following example shows how to query for each table in an SQLite database, query for the data for each table, add each non-empty table to a workbook, and export as XLSX.
The Northwind database is available in SQLite form.
Download and expand the zip archive to reveal Northwind_large.sqlite
- Install the dependencies:
$ npm i --save https://cdn.sheetjs.com/xlsx-latest/xlsx-latest.tgz better-sqlite3
- Save the following to
node.mjs
:
/* Load SQLite3 connector library */
import Database from "better-sqlite3";
/* Load SheetJS library */
import * as XLSX from 'xlsx/xlsx.mjs';
import * as fs from 'fs';
XLSX.set_fs(fs);
/* Initialize database */
var db = Database("Northwind_large.sqlite");
/* Create new workbook */
var wb = XLSX.utils.book_new();
/* Get list of table names */
var sql = db.prepare("SELECT name FROM sqlite_master WHERE type='table'");
var result = sql.all();
/* Loop across each name */
result.forEach(function(row) {
/* Get first 100K rows */
var aoo = db.prepare("SELECT * FROM '" + row.name + "' LIMIT 100000").all();
if(aoo.length > 0) {
/* Create Worksheet from the row objects */
var ws = XLSX.utils.json_to_sheet(aoo, {dense: true});
/* Add to Workbook */
XLSX.utils.book_append_sheet(wb, ws, row.name);
}
});
/* Write File */
XLSX.writeFile(wb, "node.xlsx");
- Run
node node.mjs
and opennode.xlsx
- Install the dependencies:
$ npm i --save https://cdn.sheetjs.com/xlsx-latest/xlsx-latest.tgz
- Save the following to
bun.mjs
:
/* Load SQLite3 connector library */
import { Database } from "bun:sqlite";
/* Load SheetJS library */
import * as XLSX from 'xlsx/xlsx.mjs';
import * as fs from 'fs';
XLSX.set_fs(fs);
/* Initialize database */
var db = Database.open("Northwind_large.sqlite");
/* Create new workbook */
var wb = XLSX.utils.book_new();
/* Get list of table names */
var sql = db.prepare("SELECT name FROM sqlite_master WHERE type='table'");
var result = sql.all();
/* Loop across each name */
result.forEach(function(row) {
/* Get first 100K rows */
var aoo = db.prepare("SELECT * FROM '" + row.name + "' LIMIT 100000").all();
if(aoo.length > 0) {
/* Create Worksheet from the row objects */
var ws = XLSX.utils.json_to_sheet(aoo, {dense: true});
/* Add to Workbook */
XLSX.utils.book_append_sheet(wb, ws, row.name);
}
});
/* Write File */
XLSX.writeFile(wb, "bun.xlsx");
- Run
bun bun.mjs
and openbun.xlsx