Skip to content

Commit

Permalink
only export 1st table; check for empty data
Browse files Browse the repository at this point in the history
  • Loading branch information
metawops committed Jun 3, 2022
1 parent ab42dc6 commit 3795cbf
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 57 deletions.
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ The purpose of this plugin is to be able to export table data from a pane in rea

Background: The fabulous Dataview plugin for Obsidian allows to dynamically create tables from an SQL-like query over your notes' metadata.
I wanted to be able to further use this created data in external applications, like MS Power BI, to create visualizations of that data.
But the plugin can export any table into a CSV file, even those you "hard-coded" in Markdown (if that makes sense for you).
But the plugin can export any table into a CSV file, even those you "hard-coded" in Markdown (if that makes sense for you) or those that were created by some other plugin.

## Settings

Expand All @@ -22,10 +22,12 @@ My plugin allows you to configure a few things in its settings:

* A file number addition

This gets added to the base filename (after a hyphen). After this, the extension `.csv` is added.
This number gets incremented by one after each succesful export and resetted to 001 after reaching 999.
Normally you won't need to interfere with this in the settings but you can change it if you want.
**But be careful!** Don't mess with this. Don't change this to text or something different than numbers. And stay in the ### scheme (three ciphers max., leading zeroes).
This gets added to the base filename (after a hyphen). After this, the extension `.csv` is added.
This number gets incremented by one after each succesful export and resetted to 001 after reaching 999.
Normally you won't need to interfere with this in the settings but you can change it if you want.
**But be careful!** Don't mess with this. Don't change this to text or something different than numbers. And stay in the ### scheme (three ciphers max., leading zeroes).
It may become neccessary to either change this number manually or to delete/rename/move files out of your vault folder.
No worries, though: the plugin never overwrites any files and warns you if a file already exists.

Default: `001`

Expand All @@ -49,15 +51,15 @@ My plugin allows you to configure a few things in its settings:

## Usage

The plugin adds a new command: "Export table to CSV file". This will only work when your currently active pane is in reading mode. When the command is executed a `.csv` file is written according to the settings in your vault's main folder.
The plugin adds a new command: "Export table to CSV file". This will only work when your currently active pane is in reading mode. When the command is executed a `.csv` file is written according to the settings in your vault's main folder. This CSV file contains the data of the *first* table in the reading mode of the note.

The plugin works on mobile, too. (Tested on iPadOS only, though.)

## Current limitations

Of course, there's always room for improvement. **Currently, there are the following limitations/restrictions**:

* The plugin will produce unpredictable results if your note contains more than one table. Please just make one table per note if you want to make use of this plugin in its current version.
* The plugin currently exports only the first table that it finds in the reading mode of a note.
* The plugin saves the CSV file directly into you vault's main folder. A feature to select another folder inside your vault will be added later.
* It's currently not possible to use a TAB character as a separation character.
* The quotation character is currently the double quote character `"` and cannot be changed.
Expand Down
110 changes: 62 additions & 48 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,40 +51,46 @@ export default class Table2CSVPlugin extends Plugin {
// Now convert the tables
const csvString = htmlToCSV(view.previewMode.containerEl, this.settings.sepChar, this.settings.quoteData);

const filename = `${this.settings.baseFilename}-${this.settings.fileNumber}.csv`;
this.app.vault.create(filename, csvString)
.then( () => {
// increment the file number addition string
// first, convert the current string to a number:
let fn: number = +this.settings.fileNumber;
// then increment the number:
fn++;
// don't allow more that 999; restart with 001 in that case:
if (fn==1000) fn = 1;
// convert the number to a string again:
let newFileNumberString: string = fn + "";
// add leading zeroes to the string:
while (newFileNumberString.length < 3) newFileNumberString = "0" + newFileNumberString;
this.settings.fileNumber = newFileNumberString;
if (this.settings.saveToClipboardToo) {
navigator.clipboard
.writeText(csvString)
.then(() => {
new Notice(`The file ${filename} was successfully created in your vault. The contents was also copied to the clipboard.`);
})
.catch((err) => {
new Notice('There was an error with copying the contents to the clipboard.');
});

} else {
new Notice(`The file ${filename} was successfully created in your vault.`)
}
})

.catch( (error) => {
const errorMessage = `Error: ${error.message}`;
new Notice(errorMessage);
})
// TODO: prüfen, ob csvString leer oder nicht! Nur wenn nicht, Datei anlegen etc.
if (csvString.length > 0) {
const filename = `${this.settings.baseFilename}-${this.settings.fileNumber}.csv`;
this.app.vault.create(filename, csvString)
.then( () => {
// increment the file number addition string
// first, convert the current string to a number:
let fn: number = +this.settings.fileNumber;
// then increment the number:
fn++;
// don't allow more that 999; restart with 001 in that case:
if (fn==1000) fn = 1;
// convert the number to a string again:
let newFileNumberString: string = fn + "";
// add leading zeroes to the string:
while (newFileNumberString.length < 3) newFileNumberString = "0" + newFileNumberString;
this.settings.fileNumber = newFileNumberString;
if (this.settings.saveToClipboardToo) {
navigator.clipboard
.writeText(csvString)
.then(() => {
new Notice(`The file ${filename} was successfully created in your vault. The contents was also copied to the clipboard.`);
})
.catch((err) => {
new Notice('There was an error with copying the contents to the clipboard.');
});

} else {
new Notice(`The file ${filename} was successfully created in your vault.`)
}
})

.catch( (error) => {
const errorMessage = `Error: ${error.message}`;
new Notice(errorMessage);
})
}
else {
new Notice(`No table was found. No CSV file was written.`);
}

}
else {
Expand Down Expand Up @@ -119,23 +125,31 @@ export default class Table2CSVPlugin extends Plugin {

function htmlToCSV(html: HTMLElement, sep: string, quote: boolean) {
var data = [];
var rows = html.querySelectorAll("table tr");
var table = html.querySelector("table");
console.log(`htmlToCSV::table: ${table}`);

for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");

for (var j = 0; j < cols.length; j++) {
if (!quote) {
row.push((cols[j] as HTMLElement).innerText);
} else {
row.push('"' + (cols[j] as HTMLElement).innerText + '"');
if (table) {
var rows = table.rows;
console.log(`htmlToCSV::rows: ${rows}`);
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");

for (var j = 0; j < cols.length; j++) {
if (!quote) {
row.push((cols[j] as HTMLElement).innerText);
} else {
row.push('"' + (cols[j] as HTMLElement).innerText + '"');
}
}

data.push(row.join(sep));
}

data.push(row.join(sep));
}

return data.join("\n");
}
console.log(`htmlToCSV::data.length: ${data.length}`);
if (data.length > 0)
return data.join("\n");
else
return "";
}

class Table2CSVSettingTab extends PluginSettingTab {
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "obsidian-table-to-csv-exporter",
"name": "Table to CSV Exporter",
"version": "0.1.0",
"version": "0.1.1",
"minAppVersion": "0.14.6",
"description": "This plugin allows for exporting tables from a pane in reading mode into CSV files.",
"author": "Stefan Wolfrum",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "obsidian-table-to-csv-exporter",
"version": "0.1.0",
"version": "0.1.1",
"description": "This plugin allows to export tables in a preview pane to be exported to CSV files.",
"main": "main.js",
"scripts": {
Expand Down

0 comments on commit 3795cbf

Please sign in to comment.