grails 导出 excel

用 poi 来导出 excel 文件

import org.codehaus.groovy.grails.commons.*
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.hssf.usermodel.HSSFSheet
import org.apache.poi.hssf.usermodel.HSSFRow
import org.apache.poi.hssf.usermodel.HSSFCell
import org.codehaus.groovy.grails.commons.GrailsDomainClass
import org.codehaus.groovy.grails.web.converters.ConverterUtil
import org.springframework.web.servlet.support.RequestContextUtils as RCU
import org.codehaus.groovy.grails.scaffolding.DomainClassPropertyComparator;
import org.springframework.context.MessageSource
import org.apache.poi.hssf.usermodel.HSSFCellStyle
import org.apache.poi.hssf.usermodel.HSSFFont
import org.apache.poi.hssf.util.HSSFColor;

class XlsExportService {

//    def messageSource
    MessageSource messageSource
    boolean transactional = true
//    def config = ConfigurationHolder.config
//    def domainName
    def xlsExport(out, request, domain, datas) {
        def excludedProps = ['id', 'version']
        def column = []
        def titles = []
        def outProperties
        def locale = RCU.getLocale(request)
//        def text
        def args
        def domainName = domain.toLowerCase()
        GrailsDomainClass domainClass = ConverterUtil.getDomainClass(domain)
        if (domainClass != null) {
            outProperties = domainClass.properties.findAll {!excludedProps.contains(it.name)}
        }
        Collections.sort(outProperties, new DomainClassPropertyComparator(domainClass))
        outProperties.each {
            column << "${it.name}"
            def text = messageSource.getMessage(
                    "${domainName}.${it.name}".toString(),
                    args == null ? null : args.toArray(),
                    "${domainName}.${it.name}".toString(),
                    locale)
            titles << text
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("new sheet");
        HSSFRow row
        HSSFCell cell
        HSSFCellStyle style = wb.createCellStyle()
        HSSFFont font   =   wb.createFont()
        font.setFontHeightInPoints((short)12)
        font.setFontName("宋体")
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD) 
        style.setFont(font)
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER)
        style.setFillBackgroundColor(HSSFColor.ORANGE.index)
//        style.setFillPattern(HSSFCellStyle.)
        // set the title
        row = sheet.createRow((short) 0);
        titles.eachWithIndex {title, i ->
            cell = row.createCell((short) (i));
            cell.setCellStyle(style)
            cell.setCellValue(title);
        }

        // set the data
        datas.eachWithIndex {data, i ->
            row = sheet.createRow((short) (i+1));
            column.eachWithIndex {p, j ->
                row.createCell((short) (j)).setCellValue(data."${p}");

            }

        }

        // Write the output to a file
        wb.write(out);
        out.close()

    }


}


在你的 domaincontroller 中加入

 def exportXls = {
//        def excludedProps = ['id', 'version']
//        def column = []
//        def titles = []
//        def outProperties = []
//        GrailsDomainClass domainClass = ConverterUtil.getDomainClass("Person");
//        if (domainClass != null) {
//            domainClass.persistentProperties.each {p ->
//                outProperties << p.name
//            };
//
//        }
//        outProperties.each {
//            column << "${it}"
//            titles << message(code: "person.${it}")
//        }
        response.setHeader("Content-disposition", "attachment; filename=person.xls")
        response.setContentType("application/vnd.ms-excel")
//        ServletOutputStream f = response.getOutputStream();
        xlsExportService.xlsExport(response.outputStream, request,"Person", Person.list())
//        render(contextType:"application/vnd.ms-excel")


    }


这个好处就是导出的表头信息通过 properties来获取!

你可能感兴趣的:(apache,Web,Excel,grails,groovy)