Read Styles in excel sheets in JS - javascript

is there a way to read the style of a column or cell in excel sheet in nodejs? I'm using xlsx lib but I am okay with using any other lib that provide this info. to be precise I need to know if a column or cell is bold or not while reading it.

The 'excel.js` did good job to get style and more other functions.
Demo - get B1 and C1 cell's styles.
B1 - Arial, 12 px size, bold
C1 - Calibri, 20 px, Italic
Code
const ExcelJS = require('exceljs');
const wb = new ExcelJS.Workbook();
const fileName = 'test-style.xlsx';
wb.xlsx.readFile(fileName).then(() => {
const ws = wb.getWorksheet('Sheet1');
const b1_font = ws.getCell('B1').font
console.log(b1_font);
const c1_font = ws.getCell('C2').font
console.log(c1_font);
}).catch(err => {
console.log(err.message);
});
Result
$ node read.js
{ bold: true, size: 12, color: { theme: 1 }, name: 'Arial', family: 2 }
{
size: 20,
color: { theme: 1 },
name: 'Calibri',
family: 2,
scheme: 'minor'
}
More detail information in here
and here

Related

save CSV from an array of objects in VueJs 3

I want to save an array of objects to a CSV file, I have tried the following code based on this answer, but my code didn't work well, can you please tell me how can I fix it? thanks in advance.
<template>
<div #click="saveLogs()">save csv</div>
</template>
<script>
export default {
name: "App",
components: {},
methods: {
/****************************************
* https://stackoverflow.com/a/68146412
****************************************/
arrayToCsv(data) {
return data
.map(
(row) =>
row
.map(String) // convert every value to String
.map((v) => v.replaceAll('"', '""')) // escape double colons
.map((v) => `"${v}"`) // quote it
.join(",") // comma-separated
)
.join("\r\n"); // rows starting on new lines
},
/**************************************************************
* downloadBlob(csv, 'export.csv', 'text/csv;charset=utf-8;')
*************************************************************/
downloadBlob(content, filename, contentType) {
// Create a blob
var blob = new Blob([content], { type: contentType });
var url = URL.createObjectURL(blob);
// Create a link to download it
var pom = document.createElement("a");
pom.href = url;
pom.setAttribute("download", filename);
pom.click();
},
saveLogs() {
const myLogs = this.arrayToCsv([
{ act_id: 44, actor: "robot_arm", color: "yellow", lego: "yb1", pick: {x: 1, y: 2, z:5} },
{ act_id: 44, actor: "robot_arm", color: "yellow", lego: "yb2", pick: {x: 1, y: 2, z:5} },
]);
this.downloadBlob(myLogs, "./gui_logs.csv", "text/csv;charset=utf-8;");
console.log("Logs has been saved");
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
You try to do it like it's a 2D array, but it's an array of JSON objects.
Like #traynor said, read this :
Converting JSON object to CSV
You can read this too :
JSON to CSV - Javascript client side
Also consider using npm library like csv-writer (install with npm i csv-writer). You can find out an example here.
When downloading the file, I suggest you to set content-type to 'text/csv' and filename without './'. After clicking a link you should remove it like that : pom.remove()

How to set position to label in Oracle Maps HTML5 JavaScript API

I have code like this
private _addLayer(layerName: string, featureGeometry: any, featureName: string, style: any,
featureLabel: string = '') {
const labelStyle = new OM.style.Text({
fontSize: 16,
fill: '#FF0000'
})
let layer = new OM.layer.VectorLayer(layerName, {
renderingStyle: style,
def:
{
type: OM.layer.VectorLayer.TYPE_LOCAL,
features: [new OM.Feature(featureName, featureGeometry, {label: featureLabel})]
}
})
layer.setLabelsVisible(true);
layer.setLabelingStyle(labelStyle)
this._map.addLayer(layer);
}
Just adding line and label to map.
I want change default label position (for example basement to vertical align).
But I don't find in docs information about to set label position (OM.Style.Text).
So, How can I do this?

all column not display properly in the dynamic table of pdfMake in react

I made a dynamic table in pdf make. Everything works fine, data comes from the backend and is integrated in the pdf make, but when I downloaded the PDF, some of the columns is missing and some of the column data were showing partially. Let me know what I am doing wrong.
var dd = {
content: [
{
style: 'tableExample',
table: {
body: [
['ID', 'Name', 'Amount', 'Arrival', 'Checkout', 'TotalTime','phoneNumber','extendedTime']
]
}
},
],
}
export const BookingPDFData = (data) => {
for (let i = 0; i < data.length; i++) {
let values = Object.values(data[i]);
dd.content[1].table.body.push(values);
}
return dd
}
Might be it is due to the size of your content. Size of your content is bigger to fit in portrait, if you will change the pageOrientation to landscape then it may be fit in the page. You can do it as follow:
pageSize: 'A4',
pageOrientation: 'landscape',
If this is not the case then try to adjust fontsize of your columns.

Exceljs: 'We found a problem with some content in ’filename.xlsx’.'

I am trying to render an excel file in Table format with Exceljs but I am getting this warning before opening the file:
We found a problem with some content in ’test.xlsx’. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.
If I click yes it 'recovers' the file and everything is perfect, but I always get that warning before opening.
This only happens when I do more than one tab, for a single one works fine.
import Excel from 'exceljs'
const tabs = {
'FIRST TAB': [
{ URL: 'https://google.com', FOO: 10 },
{ URL: 'https://apple.com', FOO: 12.5 }
],
'SECOND TAB': [
{ URL: 'https://google.com', FOO: 10 },
{ URL: 'https://apple.com', FOO: 22.5 }
]
}
;(async () => {
const workbook = new Excel.Workbook()
let worksheet = {}
for (const [label, tab] of Object.entries(tabs)) {
worksheet = workbook.addWorksheet(label)
worksheet.state = 'visible'
const columns = Object.keys(tab[0]).map((items) => ({
name: items,
filterButton: true
}))
const rows = tab.map((entry) => Object.values(entry))
workbook.getWorksheet(label).addTable({
name: label,
ref: 'A1',
headerRow: true,
columns,
rows
})
}
// Write to excel
await workbook.xlsx.writeFile(`test.xlsx`)
})()
The problem is caused by the space in the table name.
One way to fix it would be to replace the space with an underscore, that's actually what Excel does when it 'fixes' the file.
workbook.getWorksheet(label).addTable({
name: label.replace(' ', '_'),
ref: 'A1',
headerRow: true,
columns,
rows
})
For me, this is caused by having a cell whose content is a string with length >=32768. I have to trim the string down to 32767 bytes.

How to export ui-grid to excel file?

I use ui-grid in my project with angularjs.
In my project ui-grid exports content to excel file and it's working perfectly.
Here is ui-grid declaration:
and here ui-grid definition in javascript:
$scope.gridOptions = {
columnDefs: [
{ field: 'name' },
{ field: 'company', cellFilter: 'mapCompany:this.grid.appScope.companyCatalog' }
],
enableGridMenu: true,
enableSelectAll: true,
exporterCsvFilename: 'myFile.csv',
exporterPdfDefaultStyle: {fontSize: 9},
exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red'},
exporterPdfHeader: { text: "My Header", style: 'headerStyle' },
exporterPdfFooter: function ( currentPage, pageCount ) {
return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' };
},
exporterPdfCustomFormatter: function ( docDefinition ) {
docDefinition.styles.headerStyle = { fontSize: 22, bold: true };
docDefinition.styles.footerStyle = { fontSize: 10, bold: true };
return docDefinition;
},
exporterPdfOrientation: 'portrait',
exporterPdfPageSize: 'LETTER',
exporterPdfMaxGridWidth: 500,
exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
data : [
{
"name": "Derek",
"company": 423638
},
{
"name": "Frederik",
"company": 513560
}
],
onRegisterApi: function(gridApi){
$scope.gridApi = gridApi;
},
gridMenuCustomItems: [
{
title:'Custom Export',
action: function ($event) {
// this.grid.api.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL, true );
var exportData = uiGridExporterService.getData(this.grid, uiGridExporterConstants.ALL, uiGridExporterConstants.ALL, true);
var csvContent = uiGridExporterService.formatAsCsv([], exportData, this.grid.options.exporterCsvColumnSeparator);
uiGridExporterService.downloadFile (this.grid.options.exporterCsvFilename, csvContent, this.grid.options.exporterOlderExcelCompatibility);
},
order:0
}
]
};
Here is workin PLUNKER!
But I need to export content to RTL excel file.
My question is how can I export ui-grid content to RTL excel file?
You have two options here. You can use the built-in menu, which I just did successfully on a demo from UIGrid or you can add in another module, the ui.grid.exporter
From the documentation:
This module provides the ability to export data from the grid. Data
can be exported in a range of formats, and all data, visible data, or
selected rows can be exported, with all columns or visible columns. No
UI is provided, the caller should provide their own UI/buttons as
appropriate, or enable the gridMenu
I used the built-in gridMenu, which downloaded a file without an extension called undefined. I was able to open it as is from LibreOffice Calc.
If you want more control, depending on your use case, then use the exporter feature. The exporter feature allows data to be exported from the grid in csv or pdf format. The exporter can export all data, visible data or selected data.
If you want to export as Excel you need to have installed the Excel-Builder module, available through: bower install excelbuilder.
You are leaving out a lot in your question though. The user can set the RTL or LTR options in excel itself, depending on the version. To do it in code will take another library or program of some kind. Years ago I did a lot of MS Word and Excel programming using Visual Basic.
My point is, you need to specify the excel version, do you want to modify the file programmatically, are you sending the file somewhere or does the user download it and then they open it with excel? etc... I need more of the details for your use case.

Categories