Red de conocimiento informático - Material del sitio web - ¿Cómo escribir datos en una celda EXCEL específica usando Java?

¿Cómo escribir datos en una celda EXCEL específica usando Java?

Los utilizados en nuestro proyecto son para su referencia. Si no los hemos escrito todos, puede descargarlos usted mismo en Baidu

importar jxl.Workbook;

.

importar jxl.write.Label;

importar jxl.write.WritableImage;

importar jxl.write.WritableSheet;

importar jxl.write. WritableWorkbook;

importar jxl.write.WriteException;

importar jxl.write.biff.RowsExceededException;

/**

* Exportar Excel

* @param reportParams exportar etiqueta de nombre de columna de Excel

* @param list exportar valor de Excel

* @param headersexcel header

* @param reportName·nombre de hoja de excel

* @param respuesta

* @param startRow Desde qué fila empezar a poner valores de lista

* @ param startCol Desde qué columna comenzar a poner valores de lista

p>

* @return

*/

public boolean report(ReportBean rb, List list, encabezados XlsHeaderBean[], cadena reportName, respuesta HttpServletResponse, int startRow, int startCol, solicitud HttpServletRequest){

WritableWorkbook wwb = null;

OutputStream os;

bandera booleana = verdadero;

Fecha fecha = nueva Fecha();

Formato DateFormat = nuevo SimpleDateFormat("aaaa-MM-dd");

Cadena strDate = format.format(date);

try {

// Utilice el método de fábrica de la clase Workbook para crear un objeto de libro de trabajo

response.setContentType ("application/x-msdownload");

String hojaNombre = "reporte";

hojaNombre = hojaNombre.replaceAll(":", "").replaceAll("[) ]", "")

.replaceAll( "[(]", "");

// Explica aquí

// archivo adjunto; Esto representa qué se va a descargar Si lo elimina, puede abrirlo directamente programando

// nombre de archivo es el nombre del archivo, que es el nombre de archivo predeterminado al guardarlo o descargarlo

response.addHeader("Content-Disposition", "attachment; filename="

+ nueva cadena(sheetName.getBytes("UTF-8"), "ISO-8

859-1")+ strDate

+ ".xls");

os = respuesta.getOutputStream();

wwb = Workbook.createWorkbook(os );

} catch (IOException e) {

e.printStackTrace();

return flag = false;

}

if (wwb != null) {

// Crear una hoja de trabajo grabable

// El método createSheet de Workbook tiene dos parámetros, 1 nombre, 2 posiciones

WritableSheet ws = wwb.createSheet(reportName, 0);

//Empiece a agregar celdas a continuación

//Exportar Excel

intente {

Etiqueta labelC = null;

for(int j = 0; j < headers.length; j++){

if( headers[j] .isUnion()){

ws.mergeCells(encabezados[j].getCol(), encabezados[j].getRow(), encabezados[j].getCol()+encabezados[ j].getColLength (), encabezados[j].getRow()+headers[j].getRowLength());

}

labelC = nueva etiqueta(encabezados[j] .getCol() , encabezados[j].getRow(), encabezados[j].getValue());

ws.addCell(labelC);

}

} captura (RowsExceededException e) {

e.printStackTrace();

} captura (WriteException e) {

e.printStackTrace();

}

Valor de cadena = null;

for (int i = 0; i < list.size(); i++) {

Asignar valores ​​= (Map)list.get(i);

for (int j = 0; j < rb.getReportParams().length; j++) {

/ / Qué Lo que hay que tener en cuenta aquí es que en Excel, el primer parámetro representa la columna y el segundo parámetro representa la fila

Label labelC;

if(values.get(rb.getReportParams( )[j]) == null){

valor = "";

} más {

if(values.get(rb.getReportParams() [j]) instancia de java.util.Date){

valor = format.format(values.get(rb.getReportParams()[j]));

} más si (values.get(rb.getReportParams()[j]) instancia de java.math.BigDecimal){

valor = valores.get(rb.getReportParams()[j]).toString();

} más {

valor = valores.get(rb.getReportParams()[j ]).toString();

}

}

labelC = nueva etiqueta(j+startCol, i + startRow, valor);

pruebe {

//Agregue la celda generada a la hoja de trabajo

ws.addCell(labelC);

} catch (RowsExceededException e ) {

e.printStackTrace();

return flag = false;

} catch (WriteException e) {

e. ;

bandera de retorno = false;

}

}

}

if(rb .isHasImg( )){

String rootPath = this.getServletContext().getRealPath("savefiles");

String imgPath = rb.getImgPath();

if (rootPath != null && rootPath.compareTo("") != 0 && imgPath != null && imgPath.compareTo("") !=0){

String[] strs = imgPath .split( "\\/");

Cadena imgName = strs[strs.length-1];

Archivo archivo = nuevo Archivo(rootPath + File.separator + imgName);

if(file.exists()){

WritableImage wi = new WritableImage(0, startRow + list.size() + 2,12,20, archivo);

ws.addImage(wi);

}

}

}

prueba {

//Escribir desde la memoria al archivo

wwb.write();

wwb.close();

bandera de retorno;

p>

} catch (IOException e) {

e.printStackTrace();

bandera de retorno = false;

} catch (WriteException e) {

e.printStackTrace();

bandera de retorno = false;

}

}

bandera de retorno;

}