在 Java 中创建 Excel 文件

我想创建一个 Excel 文件并写入数据,就像用 Java 编写文本文件一样。我试图将文件扩展名从 .txt 更改为 .xls 。但我想在 Excel 文件中加粗字母。我怎样才能做到这一点?

我曾尝试使用 JXL API,但每次我必须创建一个标签时,我都不想添加任何标签。不能O编辑表格的行和列吗?

原文由 guna 发布,翻译遵循 CC BY-SA 4.0 许可协议


回答:

用easyPoi,以下是类似代码:

 @RequestMapping(value = "/exportXls")

public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {

// Step.1 组装查询条件

QueryWrapper<ExcelObject> queryWrapper = null;

try {

String paramsStr = request.getParameter("paramsStr");

if (oConvertUtils.isNotEmpty(paramsStr)) {

String deString = URLDecoder.decode(paramsStr, "UTF-8");

ExcelObject excelObject = JSON.parseObject(deString, ExcelObject.class);

queryWrapper = QueryGenerator.initQueryWrapper(excelObject, request.getParameterMap());

}

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

//Step.2 AutoPoi 导出Excel

ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());

List<ExcelObject> pageList = excelObjectService.list(queryWrapper);

//导出文件名称

mv.addObject(NormalExcelConstants.FILE_NAME, "Excel列表");

mv.addObject(NormalExcelConstants.CLASS, ExcelObject.class);

mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("Excel列表数据", "导出人:xxx", "导出信息"));

mv.addObject(NormalExcelConstants.DATA_LIST, pageList);

return mv;

}


回答:

//Find jar from here "http://poi.apache.org/download.html"

import java.io.*;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.usermodel.HSSFRow;

public class CreateExlFile{

public static void main(String[]args) {

try {

String filename = "C:/NewExcelFile.xls" ;

HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet sheet = workbook.createSheet("FirstSheet");

HSSFRow rowhead = sheet.createRow((short)0);

rowhead.createCell(0).setCellValue("No.");

rowhead.createCell(1).setCellValue("Name");

rowhead.createCell(2).setCellValue("Address");

rowhead.createCell(3).setCellValue("Email");

HSSFRow row = sheet.createRow((short)1);

row.createCell(0).setCellValue("1");

row.createCell(1).setCellValue("Sankumarsingh");

row.createCell(2).setCellValue("India");

row.createCell(3).setCellValue("sankumarsingh@gmail.com");

FileOutputStream fileOut = new FileOutputStream(filename);

workbook.write(fileOut);

fileOut.close();

workbook.close();

System.out.println("Your excel file has been generated!");

} catch ( Exception ex ) {

System.out.println(ex);

}

}

}

原文由 Sankumarsingh 发布,翻译遵循 CC BY-SA 3.0 许可协议

以上是 在 Java 中创建 Excel 文件 的全部内容, 来源链接: utcz.com/p/944840.html

回到顶部