I have an input (type="file") where the client can attach an Excel document. The problem is that I don't know how to read it to get some information I need.
If I create a File with the Excel path, I can read the information I need from the document:
@Override
public String obtenerTelefono(File excelFile) throws IOException {
File file = new File("C:\\Users\\usuario\\Desktop\\Cosas\\tlf.xls");
FileInputStream iFile = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(iFile);
HSSFSheet sheet = workbook.getSheetAt(0);
workbook.close();
return obtenerTelefono(sheet);
}
public String obtenerTelefono(HSSFSheet sheet) {
HSSFRow row = sheet.getRow(0);
int telefono = (int) row.getCell(1).getNumericCellValue();
return String.valueOf(telefono);
}
The problem is I don't know how to do this same thing when I have to work with the document attached (File excelFile) instead of the path. I have an example method, but I can't make it work for my situation:
public void importarFichero() throws IOException, IcaException {
boolean validado = validarFichero();
if (validado) {
prefijo = fichero.getFileName().split("\\.")[0];
String sufijo = fichero.getFileName().split("\\.")[1];
File file = File.createTempFile(prefijo + "_", "." + sufijo, new File(System.getProperty("java.io.tmpdir")));
OutputStream outputStream = new FileOutputStream(file);
org.apache.poi.util.IOUtils.copy(fichero.getInputstream(), outputStream);
FileInputStream inputStream = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
HSSFSheet sheet = workbook.getSheetAt(0);
List<UnidadPoblacion> unidadPoblacionImportadas = obtenerUnidadesPoblacionExcel(sheet, this.anyoEjercicio);
if (service.guardaUnidadPoblacionImportadas(unidadPoblacionImportadas)) {
if (this.getListado() != null) {
try {
loadListadoFromDDBB();
} catch (IcaException e) {
addMessageError("actualizar_multiple_error");
}
}
int resultado = service.actualizaPoblacionEjercicioBonificacion(this.anyoEjercicio.intValue(),Integer.parseInt(unidadPoblacionImportadas.get(0).getProvincia().getCodigoProvincia()));
if(resultado >= 0) {
addMessageInfo("importar_fichero_ok", (Object) fichero.getFileName());
} else {
addMessageError("importar_fichero_ok_actualizar_poblacion_error", fichero.getFileName());
}
fichero = null;
anyoEjercicio = null;
} else {
addMessageError("importar_fichero_error", fichero.getFileName());
}
}
}
I think I can't reuse this because fichero is an instance of a class named UploadedFile and I am working with File, so I don't have the getInputStream() method and I can't find a similar File method.
Do you know how I can create that temporal file with the information from the original document and then read that file? Maybe the input information I am receiving from the HTML shouldn't be stored as a File instance?
On the server side, I am using SpringMVC.
This is the HTML part:
<div class="form-group form-inline form-xtra required">
<label>Seleccionar archivo:</label>
<div required="true">
<input type="file" id="destinatarioExcel" name="destinatarioExcel" disabled="disabled"/>
</div>
</div>
This is the controller part:
@RequestMapping(value = "/guardarMensaje", method = RequestMethod.POST)
public String guardarMensaje(@Valid @ModelAttribute("mensaje") MensajeDto mensaje, @RequestParam("destinatarioExcel") File excelFile, BindingResult errors,
final RedirectAttributes attr,
final ModelMap model) throws IOException {
if (errors.hasErrors()) {
attr.addFlashAttribute("org.springframework.validation.BindingResult.mensaje", errors);
attr.addFlashAttribute("mensaje", mensaje);
}
Calendar fechaActual = Calendar.getInstance();
Date fechaSql = new Date((fechaActual.getTime()).getTime());
String hora = Integer.valueOf(fechaActual.get(Calendar.HOUR_OF_DAY)).toString();
mensaje.setIdLatiniaSMS("Prueba");
mensaje.setIdUsuario(new Long(1));
mensaje.setEstadoSMS("E");
mensaje.setFechaSMS(fechaSql);
mensaje.setHoraSMS(hora);
mensaje.setResEnvio("Prue");
mensaje.setResEnvioDec("Prue");
mensaje.setEstadoEnvio("Est");
if (mensaje.getTelfLibreta() != null) {
mensaje.setNumTlfn(mensaje.getTelfLibreta());
} else if (mensaje.getTelfManual() != null) {
mensaje.setNumTlfn(mensaje.getTelfManual());
} else if (excelFile != null) {
mensaje.setNumTlfn(this.mensajeProvider.obtenerTelefono(excelFile));
}
Boolean res;
res = this.mensajeProvider.guardarMensaje(mensaje);
if (res) {
attr.addFlashAttribute("feedback", new MensajeDto(false, "Mensaje guardado correctamente"));
} else {
attr.addFlashAttribute("feedback", new MensajeDto(true, "Error al guardar el mensaje"));
}
model.clear();
return "redirect:/mensajes";
}