博客背景:JAVA项目,将数据库内容读取创建Excel存到指定位置~
创建一个工作蒲;
创建一个表格,可以设置其中的行宽高、字体等等;
positon为文件存储位置,可以直接设置位置为磁盘中指定位置;如下默认为项目运行的上一级目录;
maps是从数据库中取出的List
读取maps循环赋值;
使用File、 FileOutputStream创建excel文件
代码如下:
public void createExcel() {String positon = "../test.xlsx";List> maps = testMapper.getTestInfo();// 定义一个新的工作簿XSSFWorkbook wb = new XSSFWorkbook();// 创建一个Sheet页,命名为firstXSSFSheet sheet = wb.createSheet("first");//设置行高sheet.setDefaultRowHeight((short) (2 * 256));//设置列宽sheet.setColumnWidth(0, 4000);sheet.setColumnWidth(1, 4000);sheet.setColumnWidth(2, 4000);XSSFFont font = wb.createFont();//设置字体font.setFontName("宋体");font.setFontHeightInPoints((short) 16);//获得表格第一行XSSFRow row = sheet.createRow(0);//根据需要给第一行每一列设置标题XSSFCell cell = row.createCell(0);cell.setCellValue("Name");cell = row.createCell(1);cell.setCellValue("Sex");cell = row.createCell(2);cell.setCellValue("Age");cell = row.createCell(3);XSSFRow rows;XSSFCell cells;//循环拿到的数据给所有行每一列设置对应的值for (int i = 0; i < maps.size(); i++) {// 在这个sheet页里创建一行rows = sheet.createRow(i + 1);nHashMap map = maps.get(i);// 该行创建一个单元格,在该单元格里设置值String name = map.get("name").toString();String sex = map.get("sex").toString();Long age = 0L;cells = rows.createCell(0);cells.setCellValue(taskName);cells = rows.createCell(1);cells.setCellValue(domain);cells = rows.createCell(2);cells.setCellValue(age);}try {//创建文件的路径File file = new File(positon);FileOutputStream fileOutputStream = new FileOutputStream(file);//将创建的表格写入wb.write(fileOutputStream);wb.close();fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}
读取本地文件,将其转成字节流 , 再转成string格式输出
positon为文件存储位置,可以直接设置位置为磁盘中指定位置;如下默认为项目运行的上一级目录;
代码如下:
String positon = "../test.xlsx";
//读取文件
InputStream is = new FileInputStream(positon);
int iAvail = is.available();
//转为字节流
byte[] bytes = new byte[iAvail];
is.read(bytes);
//转成string
String table = new String(bytes);
参考:
https://www.cnblogs.com/mythz/p/14177739.html
https://blog.csdn.net/qq_39898191/article/details/104500896