kea-react
Version:
Componentes comunes de react
49 lines (45 loc) • 1.67 kB
text/typescript
import moment = require("moment");
export type CsvCell = string | number | boolean | Date | null | undefined | {} | any[];
export type CsvRow = CsvCell[];
/**Formatea una fecha con un formato compatible con el Excel*/
function exportDate(x: Date): string {
return moment(x).format("YYYY-MM-DD HH:mm:ss");
}
/**Devuelve una celda de CSV sin el separador o las comillas */
function toCsvCell(data: CsvCell): string {
if (data == null) return "";
if (typeof data == "string") {
//quitamos las comillas y las comas
const r = data.replace(/(?:\r?\n|\r)|"|,/g, "");
return r;
} else if (typeof data == "number") {
const r = "" + data;
return r;
} else if (data instanceof Date) {
//Ya que excel no soporta el formato ISO 8601 exportamos con un formato diferente:
const r = exportDate(data);
return r;
} else if (typeof data == "boolean") {
const r = data ? "Si" : "No";
return r;
} else if (data instanceof Array) {
return data.join(", ");
} else if (typeof data == "object") {
return toCsvCell(Object.keys(data));
}
const x: never = data;
return "" + x;
}
/**Convierte una fila de datos a un CSV */
function toCsvRow(row: CsvRow) {
return row
.map(cell => "\"" + toCsvCell(cell) + "\"")
.reduce((a, b) => a == "" ? b : a + "," + b, "");
}
/**Codigo para convertir los datos a CSV */
export function toCSV(data: CsvRow[]) {
const newLine = "\r\n";
return data
.map(row => toCsvRow(row))
.reduce((a, b) => a == "" ? b : a + newLine + b, "");
}