1. Agregue la información de registro de exportación al proyecto
2. Importe el archivo JAR que opera archivos de Excel como POI-*. JAR en el proyecto
Excel Export es pasar parámetros al controlador de acuerdo con las condiciones de primer plano, consultar la base de datos de acuerdo con los parámetros, consultar la recopilación de la lista y generar datos Excle para descargar la recopilación de la lista.
Fragmento de código:
Contorller.java
/*** Información de exportación* @param modelo*/@RequestMapping ("ExportCustomer.do") @SystemControllerLog (descripción = "Forma de datos ExportExcle") public void exportCustomer (modelmap modelo) {// TODO si necesita agregar una condición //model.addattributeername ", namestr); // Obtenga los datos que se exporten Listas de la lista <CMCustomer> cusList = Customerservice.ExportCustomer (modelo); // Use el método para generar Excle Plantilla Style HSSFWorkbook Workbook = CLESSERVICE.CreateExcel (CusList, Solicitud); SimpleDateFormat Format = new SimpleDateFormat ("yyyymmddhmmss"); // Definir formato de nombre de archivo intente {// Defina el nombre excedente ISO-8859-1 para evitar una cadena confusa msg = new String (("Información del cliente_" + format.format (nueva fecha ()) + ".xls"). GetBytes (), "ISO-8859-1"); // use el tiempo de exportación como el nombre del archivo respuesta.setContentType ("Application/vnd.ms-Excel"); respuesta.AddHeader ("Disposición de contenido", "Adjunto; FileName =" + Msg); Workbook.Write (Response.getOutputStream ()); } catch (ioException e) {logger.error (e); }} 2. Método CreateExcel en servicio
public HSSFWorkBook CreateExcel (List <CmCustomer> CusList, HttpServletRequest solicitud) {// Cree un libro web, correspondiente a un archivo de Workbook de HSSFWorkBook de Excel = nuevo HSSFWorkBook (); // Agregar una hoja en el libro web, correspondiente a la hoja en el archivo de Excel hssfsheet sheet = workbook.createSheet ("Tabla de información del cliente"); // establecer la hoja de ancho de la columna.setColumnWidth (0, 25 * 100); sheet.setColumnWidth (1, 35 * 100); sheet.setColumnWidth (2, 35 * 100); sheet.setColumnWidth (3, 40 * 100); sheet.setColumnWidth (4, 45 * 100); sheet.setColumnWidth (5, 45 * 100); sheet.setColumnWidth (6, 50 * 100); sheet.setColumnWidth (7, 80 * 100); sheet.setColumnWidth (8, 35 * 100); sheet.setColumnWidth (9, 40 * 100); // Agregar la fila 0 del encabezado en la hoja hssfrow row = sheet.createrow (0); // Crear una celda, configure el encabezado de la tabla, configure el encabezado de la tabla en el centro HSSFCellStyle Style = Workbook.CreateCellStyle (); // crear un formato centrado estilo.setalignment (hssfcellstyle.align_center); // con estilo de borde.setBorderBottom (hssfcellstyle.border_thin); // Generar una fuente hssffont font = workbook.createFont (); // Fuente engrosamiento de la fuente. // Fuente Tamaño de la fuente. // aplica la fuente al estilo de estilo actual.setFont (fuente); // Establecer toda la columna en el centro o dejar por separado hssfcellstyle style1 = workbook.createCellStyle (); style1.setalignment (hssfcellstyle.align_center); Hssfcellstyle style2 = workbook.createCellStyle (); style2.setalignment (hssfcellstyle.align_left); Hssfcellstyle style3 = workbook.createCellStyle (); style3.setalignment (hssfcellstyle.align_left); Hssffont hssffont = workbook.createFont (); hssffont.setColor (hssffont.color_red); HSSFFONT.SetBoldWeight (hssffont.boldweight_bold); style3.setFont (hssffont); Hssfcellstyle style4 = workbook.createCellStyle (); style4.setalignment (hssfcellstyle.align_left); Hssffont hssffont1 = workbook.createFont (); hssffont1.setColor (hssffont.color_normal); HSSFFONT1.SetBoldWeight (hssffont.boldweight_bold); style4.setFont (hssffont1); HSSFCell Cell = Row.CreateCell (0); Cell.SetCellValue ("Número de serie"); Cell.SetCellStyle (estilo); celular = fila.createCell (1); Cell.SetCellValue ("Nombre del cliente"); Cell.SetCellStyle (estilo); celda = fila.createCell (2); Cell.SetCellValue ("Género"); Cell.SetCellStyle (estilo); celular = fila.createCell (3); Cell.SetCellValue ("Estado"); Cell.SetCellStyle (estilo); celular = fila.createCell (4); Cell.SetCellValue ("Teléfono"); Cell.SetCellStyle (estilo); celda = fila.createCell (5); Cell.setCellValue ("buzón"); Cell.SetCellStyle (estilo); celular = fila.createCell (6); Cell.SetCellValue ("Dirección"); Cell.SetCellStyle (estilo); for (int i = 0; i <cusList.Size (); i ++) {String logTypedis = ""; fila = sheet.createrow (i + 1); Cmcustomer cmcustomer = cusList.get (i); // Crear una celda y establecer el valor // La columna numerada está en la izquierda hssfcell c1 = row.createCell (0); c1.setCellStyle (style2); c1.setCellValue (i); Hssfcell c2 = row.createCell (1); C2.SetCellStyle (Style1); C2.SetCellValue (cmcustomer.getCustomername ()); // Nombre del cliente String String Sexstr = CMCustomer.getSEx (); // Gender 0: femenino, 1: String masculino sexo = ""; if ("1" .equals (sexstr)) {sex = "masculino"; } if ("0" .equals (sexstr)) {sex = "femenino"; } Hssfcell c3 = row.createCell (2); // gender c3.setCellStyle (style1); C3.SetCellValue (sexo); String statusStr = cmcustomer.getStatus (); // Estado del cliente 1. On-the-Job, 2. Deja string status = ""; if ("1" .equals (statusstr)) {status = "on-the-jun"; } if ("2" .equals (statusStr)) {status = "renunciar"; } Hssfcell c4 = row.createCell (3); // status c4.setCellStyle (style1); c4.setCellValue (estado); String CustomerId = cmCustomer.getCustomerId (); // Lista de identificación del cliente <Cmphone> PhoneList = cmphonEmapper.SelectByCustomerId (CustomerId); String phone = ""; if (PhoneList! = NULL && PhoneList.Size ()> 0) {for (int j = 0; j <phonelist.size (); j ++) {phone = phonelist.get (j) .getphone (); }} Hssfcell c5 = row.createCell (4); // telect c5.setCellStyle (style1); c5.setCellValue (teléfono); Lista <cmemail> EMAILLIST = CMEMAILMAPPER.Selectall (CustomerId); String Correo electrónico = ""; if (EMAILLIST! = NULL && EMAILLIST.SIZE ()> 0) {for (int j = 0; j <eMaillist.size (); j ++) {Email = Emaillist.get (j) .getEmail (); }} Hssfcell c6 = row.createCell (5); // Correo electrónico C6.SetCellStyle (style1); c6.SetCellValue (correo electrónico); Cmaddress cmaddress = new cmaddress (); cmaddress.setCustomerId (CustomerId); List <cmaddress> addersSlist = cmaddressMapper.selectall (cmaddress); String Adderss = ""; if (adgressslist! = null && addersslist.size ()> 0) {for (int j = 0; j <addersslist.size (); j ++) {admitss = addersSlist.get (j) .getAddress (); }} Hssfcell c7 = row.createCell (6); // dirección c7.setCellStyle (style1); c7.setCellValue (admites); // use la fila de formato predeterminada. fila.createCell (2) .setCellValue (sexo); Row.CreateCell (3) .SetCellValue (estado); Row.CreateCell (4) .SetCellValue (teléfono); Row.CreateCell (5) .SetCellValue (correo electrónico); Row.CreateCell (6) .SetCellValue (admites); } Libro de trabajo de retorno; } 3. Página JSP Llamada
// Función de información de exportación exporbtn () {$ .AJAX ({type: "post", url: "<%= path%>/customer/exportcustomer.do", éxito: function (data) {window.open ('<%= path%>/customer/exportcustomer.do');}}); }Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.