1. Adicione informações de log de exportação ao projeto
2. Importar o arquivo JAR que opera arquivos do Excel, como Poi-*. Jar no projeto
A Exportação do Excel deve passar os parâmetros para o controlador de acordo com as condições do primeiro plano, consultar o banco de dados de acordo com os parâmetros, consultar a coleção de listas e gerar dados da Excle para baixar a coleção de listas.
Trenó de código:
Contorller.java
/*** Informações de exportação* Modelo @param*/@RequestMapping ("exportCustomer.do") @SystemControllerLog (Descrição = "Formulário do banco de dados ExportExcle") public void ExportCustomer (ModelMap Model) {// TODO Se você precisar adicionar uma condição //model.addatTrtTtrint("USTNO'Rnia " // Obtenha os dados a serem exportados LISTA LISTA <cmcustomer> Cuslist = CustomerService.ExportCustomer (Model); // Use o método para gerar o estilo Excle Modelo HSSFWorkbook Workbook = CustomerService.Createexcel (CUSLIST, solicitação); SimpledateFormat format = new SimpleDateFormat ("yyyymmddhhmmss"); // Defina o nome do arquivo formato tente {// define o nome da exclos ISO-8859-1 para impedir que a string iluminada msg = new String ("Cliente Information_" + Format.Format (new Date ()) + ".xls"). GetBytes (), "ISO-8859-1"); // Use o tempo de exportação como o nome do arquivo Response.SetContentType ("Application/vnd.ms-Excel"); Response.AddHeader ("Content-Disposition", "Applement; filename =" + msg); Work.write (Response.getOutputStream ()); } catch (ioexception e) {logger.error (e); }} 2. Método Createexcel em serviço
public HSSFWorkbook CreateExcel (List <cmcustomer> Cuslist, httpServletRequest Request) {// Crie um webbook, correspondendo a um arquivo de trabalho do Excel File HSSFWorkbook = New HSSFWorkbook (); // Adicione uma folha no webbook, correspondendo à planilha na folha do Excel File HSSFSheet = Work.CreateSheet ("Tabela de informações do cliente"); // Defina a largura da coluna. 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); // Adicione a linha 0 do cabeçalho na folha hssfrow line = sheet.crerowroow (0); // Crie uma célula, defina o cabeçalho da tabela, defina o cabeçalho da tabela para o centro HSSFCellStyle Style = Work.CreateCellStyle (); // crie um estilo de formato centrado.Setalignment (hssfcellstyle.align_center); // com border style.setborderbottom (hssfcellstyle.border_thin); // gerar uma fonte Hssffont = book.createFont (); // fontes espessando font.setBoldweight (hssffont.Boldweight_bold); // fontes size font.setFoTheightInPoints ((curto) 12); // Aplique a fonte ao estilo atual.setFont (font); // Defina a coluna inteira como centralizada ou deixada separadamente HSSFCellStyle Style1 = Work.CroateCellStyle (); style1.setalignment (hssfcellstyle.align_center); HSSFCellStyle Style2 = Workbook.CreateCellStyle (); Style2.Setalignment (HSSFCellStyle.align_left); HSSFCellStyle Style3 = Workbook.CreateCellStyle (); Style3.Setalignment (hsSfCellStyle.align_left); Hssfffont hssffont = workbook.createFont (); hssfffont.setColor (hssffont.color_red); hssfffont.setBoldweight (hssffont.Boldweight_bold); style3.setFont (Hssffont); HSSFCellStyle Style4 = Workbook.CreateCellStyle (); Style4.Setalignment (HSSFCellStyle.align_left); Hssffont Hssffont1 = Workbook.CreateFont (); hssfffont1.setColor (hssffont.color_normal); hssfffont1.setBoldweight (hssffont.Boldweight_bold); Style4.SetFont (HSSFFONT1); HSSFCell Cell = Row.CreateCell (0); Cell.SetCellValue ("Número de série"); Cell.setCellStyle (estilo); célula = linha.createCell (1); Cell.SetCellValue ("Nome do cliente"); Cell.setCellStyle (estilo); célula = linha.createCell (2); Cell.SetCellValue ("Gênero"); Cell.setCellStyle (estilo); célula = linha.createCell (3); Cell.SetCellValue ("Status"); Cell.setCellStyle (estilo); célula = linha.createCell (4); Cell.SetCellValue ("Telefone"); Cell.setCellStyle (estilo); célula = linha.createCell (5); Cell.SetCellValue ("Caixa de correio"); Cell.setCellStyle (estilo); célula = linha.createCell (6); Cell.SetCellValue ("Endereço"); Cell.setCellStyle (estilo); for (int i = 0; i <cuslist.size (); i ++) {string logtypedis = ""; linha = chaphe.creterow (i + 1); Cmcustomer cmcustomer = cuslist.get (i); // Crie uma célula e defina o valor // A coluna numerada está à esquerda hssfcell c1 = row.createCell (0); C1.setCellStyle (Style2); c1.setCellValue (i); Hssfcell c2 = linha.createCell (1); C2.SetCellStyle (Style1); c2.setCellValue (cmcustomer.getCustomername ()); // nome do cliente string sexstr = cmcustomer.getSex (); // gênero 0: fêmea, 1: sexo masculino de sexo = ""; if ("1" .Equals (sexStr)) {sex = "masculino"; } if ("0" .equals (sexstr)) {sex = "feminino"; } Hssfcell c3 = row.createCell (2); // gênero c3.setCellStyle (style1); C3.SetCellValue (sexo); String statusstr = cmcustomer.getStatus (); // status do cliente 1. On-the-job, 2. Deixe a string status = ""; if ("1" .equals (statusstr)) {status = "on-the-job"; } if ("2" .equals (statusstr)) {status = "Renign"; } Hssfcell c4 = row.createCell (3); // status c4.setCellStyle (style1); C4.SetCellValue (status); String CustomerId = cmcustomer.getCustomerId (); // Lista de ID do cliente <Cmphone> PhoneList = cmphoneMapper.SelectByCustomerID (CustomerId); String Phone = ""; if (fonelist! }} Hssfcell c5 = row.createCell (4); // Telelect c5.SetCellStyle (style1); c5.setCellValue (telefone); List <cmemail> emaillist = cmemailmapper.leclectall (clienteID); String email = ""; if (emaillist! = null && emaillist.size ()> 0) {for (int j = 0; j <emaillist.size (); j ++) {email = emaillist.get (j) .getEmail (); }} Hssfcell c6 = row.createCell (5); // emailbox c6.setCellStyle (style1); c6.setCellValue (email); Cmaddress cmaddress = new cmaddress (); cmaddress.setCustomerId (CustomerID); List <cmaddress> addSslist = cmaddressmapper.Selectall (cmaddress); String addhers = ""; if (addserSslist! = null && addserSslist.size ()> 0) {for (int j = 0; j <addserSslist.size (); j ++) {addsers = addersslist.get (j) .getAddress (); }} Hssfcell c7 = row.createCell (6); // endereço c7.setCellStyle (style1); c7.setCellValue (Adders); // Use o formato padrão. Row.CreateCell (2) .SetCellValue (sexo); row.createCell (3) .setCellValue (status); row.createCell (4) .setCellValue (telefone); row.createCell (5) .setCellValue (email); row.createCell (6) .setCellValue (adders); } retornar pasta de trabalho; } 3. Chamada de página JSP
// Exportar informações da função Exporbtn () {$ .ajax ({type: "post", url: "<%= caminho%>/cliente/exportcustomer.do", sucesso: function (data) {window.open ('<%= caminho%>/cliente/exportcustomer.do');}}); }O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.