Cómo generar informes (archivos Excel) usando java
Este es un ejemplo de exportación de datos de Tabel a Excel: puedes encontrar el paquete jxl.jar en línea. Si no lo encuentras, también puedes dejarme un correo electrónico. se lo enviará
importar java.io.File;
importar java.io.IOException;
importar java.text.SimpleDateFormat;
importar java.util .Date;
importar javax.swing.JOptionPane;
importar javax.swing.JTable;
importar jxl.Workbook ;
importar jxl.format.Alignment;
importar jxl.format.Colour;
importar jxl.format.UnderlineStyle;
importar jxl.format.VerticalAlignment;
importar jxl.read.biff.BiffException;
importar jxl.write.Label;
importar jxl.write.WritableCellFormat ;
importar jxl.write.WritableFont;
importar jxl.write.WritableSheet;
importar jxl.write.WritableWorkbook;
import jxl.write.WriteException;
clase pública TableToExcel {
exportación nula estática pública (archivo de archivo, encabezado de cadena, nota de cadena, tabla JTable) {
WritableWorkbook workbook = null;// Crear libro de trabajo
prueba {
if(file.exists()) {//Si el archivo existe
workbook = Workbook .createWorkbook(archivo, Workbook.getWorkbook (archivo));
} else {//Si el archivo no existe
workbook = Workbook.createWorkbook(archivo);
}
// Crear una hoja de trabajo
Hoja WritableSheet = workbook.createSheet(heading, workbook.getNumberOfSheets());
//Obtener el número de filas y columnas de jtable
int rowNum = table.getRowCount();
int colNum = table.getColumnCount();
fillHeader(sheet ,heading,colNum);//Completa el título principal
fillColName(sheet,table,colNum);//Completa el nombre de la columna
fillCell(sheet,table,c
olNum,rowNum);//Completa los datos
fillNote(sheet,note,colNum,rowNum);//Completa el archivo de firma
workbook.write();/ /Escribe los datos
workbook.close();//Cerrar
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Por favor cierra el trabajo antes de importar la tabla de datos");
} catch (BiffException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
/**
* Complete el título de la tabla
* @param hoja
* @param encabezado
* @param colNum
* @throws WriteException
*/ p>
fillHeader vacío estático privado (hoja WritableSheet, encabezado de cadena, int colNum) lanza WriteException {
fuente WritableFont = new WritableFont(WritableFont.ARIAL, 18, WritableFont. BOLD,false, UnderlineStyle.NO_UNDERLINE, Color.BLACK);//Establecer fuente
formato WritableCellFormat = new WritableCellFormat(font);//Nuevo objeto de formato
format.setAlignment(Alignment .CENTRE);// Establecer alineación central horizontal
format.setVerticalAlignment(VerticalAlignment.CENTRE);//Establecer alineación central vertical
sheet.mergeCells(0,0, colNum-1 , 0);// Fusionar celdas
sheet.setRowView(0, 600); // Establecer altura de fila
sheet.addCell(new Label(0,0,heading,format) ));// Complete el título principal
}
/**
* Complete los nombres de las columnas
* @ hoja de parámetros
* @param table
* @param colNum
* @throws WriteException
*/
fillColName vacío estático privado (hoja WritableSheet, tabla JTable, int colNum) lanza WriteException {
fuente WritableFont = new WritableFont(WritableFont.ARIAL,12,WritableFont.NO_BOLD);//Establecer
Font
WritableCellFormat format = new WritableCellFormat(font);//Nuevo objeto de formato
format.setAlignment(Alignment.CENTRE);//Establecer alineación central horizontal
hoja.setColumnView(0, 15);//Establecer ancho de columna
for(int col = 0; col < colNum;col++) {
Etiqueta colName = nueva Etiqueta( col ,1,table.getModel().getColumnName(col),formato);
hoja.addCell(colName);
}
} p >
/**
*Rellena los datos del formulario para excel
* @param hoja
* @param tabla
* @param colNum
* @param rowNum
* @throws WriteException
*/
celda de relleno vacía estática privada (hoja WritableSheet , JTable table,int colNum,int rowNum) lanza WriteException {
WritableFont font = new WritableFont(WritableFont.ARIAL,12,WritableFont.NO_BOLD);//Establecer la fuente
WritableCellFormat format = new WritableCellFormat(font);//Crear un nuevo objeto de formato
format.setAlignment(Alignment.CENTRE);//Establecer centrado horizontal
for(int col = 0; col < colNum ;col++) {
for(int fila = 1;fila <= filaNum -1;fila++) {//Completa los datos
Valor de cadena = "";
if(table.getModel().getValueAt(fila -1, columna) != nulo)
valor = table.getModel().getValueAt(fila -1, columna) .toString();
hoja.addCell(nueva etiqueta(col,fila + 1,valor));
}
}
}
p>/**
* Rellenar el archivo de firma
* @param hoja
* @param inscribe
* @ param colNum
* @param rowNum
* @throws WriteException
*/
privado relleno de vacío estáticoNota (hoja de hoja de escritura, inscripción de cadena, int colNum, int filaN
um) lanza WriteException {
if( inscribe == null || inscribe.length() < 1 ) {
inscribe = "Tiempo de exportación: "+ new SimpleDateFormat("yyyy- MM-dd HH:mm:ss").format(new Date());
}
fuente WritableFont = new WritableFont(WritableFont.ARIAL, 9, WritableFont.NO_BOLD,
false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// Definir fuente
Formato WritableCellFormat = new WritableCellFormat(font);// Definir objeto de formato
format.setAlignment(Alignment.RIGHT);//Visualización central horizontal
sheet.mergeCells(0, rowNum+3, colNum - 1, rowNum+3);//Fusionar celdas
hoja.addCell(new Label(0, rowNum+3, inscribe, format));// Complete la hoja de trabajo
}
}