Skip to content

Commit

Permalink
feat: add read and write xl functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jackfiszr committed Oct 23, 2024
1 parent 113b137 commit 4a7b442
Show file tree
Hide file tree
Showing 6 changed files with 150 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.xlsx
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# pl2xl
# pl2xl
12 changes: 12 additions & 0 deletions deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@jackfiszr/pl2xl",
"version": "0.0.1",
"exports": "./mod.ts",
"tasks": {
"dev": "deno run --watch main.ts"
},
"imports": {
"polars": "npm:nodejs-polars@0.16.0",
"xlsx": "npm:xlsx@0.18.5"
}
}
95 changes: 95 additions & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import pl from "polars";
import xlsx from "xlsx";

function readExcel(filePath: string): pl.DataFrame {
const workbook = xlsx.readFile(filePath);
const sheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = xlsx.utils.sheet_to_json(sheet);
return pl.DataFrame(jsonData);
}

function writeExcel(df: pl.DataFrame, filePath: string): void {
const rows = df.toRecords();
const newWorkbook = xlsx.utils.book_new();
const newSheet = xlsx.utils.json_to_sheet(rows);
xlsx.utils.book_append_sheet(newWorkbook, newSheet, "Sheet1");
xlsx.writeFile(newWorkbook, filePath);
}

export { readExcel, writeExcel };
22 changes: 22 additions & 0 deletions test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { readExcel, writeExcel } from "./mod.ts";
import pl from "polars";

const inputDf = pl.DataFrame({
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["New York", "Los Angeles", "Chicago"],
});

writeExcel(inputDf, "input.xlsx");

const df = readExcel("input.xlsx");
console.log("Read DataFrame:", df);

const modifiedDf = df.withColumn(
pl.col("Age").add(1).alias("Age"),
);

console.log("Modified DataFrame:", modifiedDf);

writeExcel(modifiedDf, "output.xlsx");
console.log("Modified DataFrame written to output.xlsx");

0 comments on commit 4a7b442

Please sign in to comment.