HSSFWorkbook创建excel文件,通过FileOutPutStream下载excel到本地

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Arrays;

public class Test2ExportExcel {
    public static void main(String[] args) throws IOException {

        //创建一个HSSFWorkbook对象
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        //通过HSSFWorkbook对象创建一个表
        HSSFSheet hssfSheet = hssfWorkbook.createSheet();
        //设置横向单元格格式
        hssfSheet.setColumnWidth(0,10000);
        hssfSheet.setColumnWidth(1,10000);
        hssfSheet.setColumnWidth(2,1000);
        //我的理解是创建第一行
        HSSFRow row0 = hssfSheet.createRow(0);
        HSSFCell cell = row0.createCell(0);
        cell = row0.createCell(0);
        //目录
        cell.setCellValue(new HSSFRichTextString("第一格"));
        cell = row0.createCell(1);
        cell.setCellValue(new HSSFRichTextString("第二格"));
        cell = row0.createCell(2);
        cell.setCellValue(new HSSFRichTextString("第三格"));
        //创建一个二维数组
        String [][] User = {{"1","2","3"},{"6","9","7"},{"31","91","71"}
        ,{"qq","ss","xx","cc"}};
        System.out.println(User);
        for(int i=0;i<User.length;i++){
            //for循环将数组写入对应的单元格,一共设置了3格,多出的数组不会显示
            HSSFRow row = hssfSheet.createRow(i+1);
            System.out.println("第"+i+"次循环");
            cell = row.createCell(0);
            cell.setCellValue(new HSSFRichTextString(String.valueOf(User[i][0])));
            System.out.println(cell);
            cell = row.createCell(1);
            cell.setCellValue(new HSSFRichTextString(String.valueOf(User[i][1])));
            System.out.println(cell);
            cell = row.createCell(2);
            cell.setCellValue(new HSSFRichTextString(String.valueOf(User[i][2])));
            System.out.println(cell);
            System.out.println("----------------------------");
        }
        String filename = "下载文件";
        //创建一个输出流,输出的位置,加文件名称,.xls这个表示是excel的格式。不加这个指定使用wps或者excel也可以打开,指定之后直接打开
        FileOutputStream outputStream = new FileOutputStream("E:\\"+filename+".xls");
        //将文件写到磁盘对应的位置
        hssfWorkbook.write(outputStream);
        System.out.println("文件已经下载");
        outputStream.close();

    }
}

 

posted @ 2022-07-27 10:20  LoveYouLoveMe  阅读(1680)  评论(0编辑  收藏  举报