Convertir CSV, TSV y TXT a Excel
Abriendo Archivos CSV
Los archivos de valores separados por comas (CSV) contienen registros cuyos valores están delimitados o separados por comas. En los archivos CSV, los datos se almacenan en un formato tabular que tiene campos separados por el carácter de coma y entrecomillados por el carácter de comillas dobles. Si el valor de un campo contiene un carácter de comillas dobles, se escapa con un par de caracteres de comillas dobles. También puede usar Microsoft Excel para exportar los datos de su hoja de cálculo a un archivo CSV.
Para abrir archivos CSV, use la clase LoadOptions y seleccione el valor CSV, predefinido en la enumeración LoadFormat.
Ejemplo
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(OpeningCSVFiles.class) + "loading_saving/"; | |
// Opening CSV Files | |
// Creating and CSV LoadOptions object | |
LoadOptions loadOptions4 = new LoadOptions(LoadFormat.CSV); | |
// Creating an Workbook object with CSV file path and the loadOptions | |
// object | |
Workbook workbook6 = new Workbook(dataDir + "Book_CSV.csv", loadOptions4); | |
// Print message | |
System.out.println("CSV format workbook has been opened successfully."); |
Abriendo Archivos CSV y reemplazando caracteres inválidos
En Excel, cuando se abre un archivo CSV con caracteres especiales, estos se reemplazan automáticamente. Lo mismo hace la API de Aspose.Cells, que se muestra en el ejemplo de código que se muestra a continuación.
Ejemplo
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
//Source directory | |
String dataDir = Utils.getSharedDataDir(OpeningCSVFilesAndReplacingInvalidCharacters.class) + "LoadingSavingConvertingAndManaging/"; | |
LoadOptions loadOptions = new LoadOptions(LoadFormat.CSV); | |
//Load CSV file | |
Workbook workbook = new Workbook(dataDir + "[20180220142533][ASPOSE_CELLS_TEST].csv", loadOptions); | |
System.out.println(workbook.getWorksheets().get(0).getName()); // (20180220142533)(ASPOSE_CELLS_T | |
System.out.println(workbook.getWorksheets().get(0).getName().length()); // 31 | |
System.out.println("CSV file opened successfully!"); |
Apertura de archivos CSV utilizando un analizador preferido
No siempre es necesario utilizar la configuración de analizador predeterminada para abrir los archivos CSV. A veces, la importación de un archivo CSV no crea la salida esperada, como el formato de fecha no es el esperado o los campos vacíos se manejan de manera diferente. Con este fin, TxtLoadOptions.PreferredParsers está disponible para proporcionar su propio analizador preferido para analizar diferentes tipos de datos según el requisito. El siguiente código de ejemplo demuestra el uso del analizador preferido.
Se pueden descargar los archivos fuente de muestra y los archivos de salida de las siguientes conexiones para probar esta función.
outputsamplePreferredParser.xlsx
Ejemplo
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
class TextParser implements ICustomParser | |
{ | |
@Override | |
public Object parseObject(String s) { | |
return s; | |
} | |
@Override | |
public String getFormat() { | |
return ""; | |
} | |
} | |
class DateParser implements ICustomParser { | |
@Override | |
public Object parseObject(String s) { | |
Date myDate = null; | |
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); | |
try { | |
myDate = formatter.parse(s); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
} | |
return myDate; | |
} | |
@Override | |
public String getFormat() { | |
return "dd/MM/yyyy"; | |
} | |
} | |
public class OpeningCSVFilesWithPreferredParser { | |
//Source directory | |
private static String sourceDir = Utils.Get_SourceDirectory(); | |
private static String outputDir = Utils.Get_OutputDirectory(); | |
public static void main(String[] args) throws Exception { | |
// Initialize Text File's Load options | |
TxtLoadOptions oTxtLoadOptions = new TxtLoadOptions(LoadFormat.CSV); | |
// Specify the separatot character | |
oTxtLoadOptions.setSeparator(','); | |
// Specify the encoding scheme | |
oTxtLoadOptions.setEncoding(Encoding.getUTF8()); | |
// Set the flag to true for converting datetime data | |
oTxtLoadOptions.setConvertDateTimeData(true); | |
// Set the preferred parsers | |
oTxtLoadOptions.setPreferredParsers(new ICustomParser[] { new TextParser(), new DateParser() }); | |
// Initialize the workbook object by passing CSV file and text load options | |
Workbook oExcelWorkBook = new Workbook(sourceDir + "samplePreferredParser.csv", oTxtLoadOptions); | |
// Get the first cell | |
Cell oCell = oExcelWorkBook.getWorksheets().get(0).getCells().get("A1"); | |
// Display type of value | |
System.out.println("A1: " + getCellType(oCell.getType()) + " - " + oCell.getDisplayStringValue()); | |
// Get the second cell | |
oCell = oExcelWorkBook.getWorksheets().get(0).getCells().get("B1"); | |
// Display type of value | |
System.out.println("B1: " + getCellType(oCell.getType()) + " - " + oCell.getDisplayStringValue()); | |
// Save the workbook to disc | |
oExcelWorkBook.save(outputDir + "outputsamplePreferredParser.xlsx"); | |
System.out.println("OpeningCSVFilesWithPreferredParser executed successfully.\r\n"); | |
} | |
private static String getCellType(int type){ | |
if(type == CellValueType.IS_STRING){ | |
return "String"; | |
} else if(type == CellValueType.IS_NUMERIC){ | |
return "Numeric"; | |
} else if(type == CellValueType.IS_BOOL){ | |
return "Bool"; | |
} else if(type == CellValueType.IS_DATE_TIME){ | |
return "Date"; | |
} else if(type == CellValueType.IS_NULL){ | |
return "Null"; | |
} else if(type == CellValueType.IS_ERROR){ | |
return "Error"; | |
} else{ | |
return "Unknown"; | |
} | |
} |
Apertura de archivos TSV (delimitados por tabuladores)
Los archivos delimitados por tabuladores contienen datos de hojas de cálculo pero sin ningún formato. Los datos están organizados en filas y columnas, como tablas y hojas de cálculo. En resumen, un archivo delimitado por tabuladores es un tipo especial de archivo de texto sin formato con una pestaña entre cada columna en el texto.
Para abrir archivos delimitados por tabuladores, los desarrolladores deben usar la clase LoadOptions y seleccionar el valor TSV, predefinido en la enumeración LoadFormat.
Ejemplo
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(OpeningTabDelimitedFiles.class) + "loading_saving/"; | |
// Creating and TAB_DELIMITED LoadOptions object | |
LoadOptions loadOptions5 = new LoadOptions(LoadFormat.TSV); | |
// Creating an Workbook object with Tab Delimited text file path and the | |
// loadOptions object | |
Workbook workbook7 = new Workbook(dataDir + "Book1TabDelimited.txt", loadOptions5); | |
// Print message | |
System.out.println("Tab Delimited workbook has been opened successfully."); |