Java Excel导出小例子

本文介绍了一个使用Java实现的简单Excel导出示例。该示例通过Apache POI库创建了一个包含表头和数据的Excel文件,并设置了样式、合并单元格及自动调整列宽等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package demo.excel;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.RegionUtil;

public class ExportExcel {
/**
* 测试数据导出
* @param args
*/
public static void main(String[] args) {

//设置列头名称和表体数据
String[] rowsName = new String[]{"项目类型","计费单量","单价(元)","金额合计(元)"};
List<Object[]>  dataList = new ArrayList<Object[]>();
Object[] obj = new Object[rowsName.length];
obj[0] = "进口商品";
obj[1] = "100";
obj[2] = "50";
obj[3] = "5000";
dataList.add(obj);
obj = new Object[rowsName.length];
obj[0] = "出口商品";
obj[1] = "200";
obj[2] = "30";
obj[3] = "6000";
dataList.add(obj);

//设置列头名称和表体数据
HSSFWorkbook workbook = setWorkBookDate(dataList,rowsName);
try {
// 将workbook对象输出到文件test.xls
FileOutputStream fos = new FileOutputStream("d:/SS/test.xls");
workbook.write(fos);
fos.flush(); // 缓冲
fos.close(); // 关闭流
}catch (Exception e1) {
e1.printStackTrace();

}
/**
* 设置excel数据
* @param dataList  表体数据
* @param titleName 列名
* @return
*/
@SuppressWarnings("deprecation")
private static HSSFWorkbook setWorkBookDate(List<Object[]>  dataList,String[] rowsName){

//创建工作簿对象
HSSFWorkbook workbook = new HSSFWorkbook();
//创建工作表,设置当前页名称
HSSFSheet sheet = workbook.createSheet("账单汇总");
//设置默认行高
sheet.setDefaultRowHeight((short)350);
//合并表头表尾的单元格
sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 3));
sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 3));
//冻结行
workbook.getSheetAt(0).createFreezePane(0, 4);
RegionUtil.setBorderBottom(1, new CellRangeAddress(3, 3, 0, 3), workbook.getSheetAt(0), workbook);//设置边框
// 获取表头样式对象
        HSSFCellStyle topStyle = getTopStyle(workbook);
        // 获取表体样式对象
        HSSFCellStyle style = getCommonStyle(workbook);
        
// 定义所需列数
int columnNum = rowsName.length;
//创建列头
HSSFRow rowHead = sheet.createRow(columnNum);  
for(int n = 0;n < columnNum;n++){
HSSFCell cellRow = rowHead.createCell(n,HSSFCell.CELL_TYPE_STRING);//创建列头对应个数的单元格
cellRow.setCellValue(rowsName[n]);//设置列头单元格的值
cellRow.setCellStyle(style);//设置列头单元格样式
}

        //设置表头的数据
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0,HSSFCell.CELL_TYPE_STRING);
    cellTiltle.setCellStyle(topStyle);
    cellTiltle.setCellValue("深圳某某科技有限公司\r\n电子数据传输服务费账单\r\n计费期:2018年03月01日-2018年04月01日");
   
    HSSFRow rowm3 = sheet.createRow(3);
        HSSFCell cellTiltle3 = rowm3.createCell(0,HSSFCell.CELL_TYPE_STRING);
    cellTiltle3.setCellStyle(topStyle);
    cellTiltle3.setCellValue("客户:"+"深圳某某公司");

//将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){
Object[] obj =new Object[dataList.get(i).length];
obj[0] = dataList.get(i)[0];
obj[1] = dataList.get(i)[1];
obj[2] = dataList.get(i)[2];
obj[3] = dataList.get(i)[3];
HSSFRow row = sheet.createRow(i+5);//创建所需的行数
for(int j = 0; j < obj.length; j++){
HSSFCell cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);//设置单元格的数据类型   
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString());//设置单元格的值
}else{
cell.setCellValue("");//设置单元格的值为空字符串
}
cell.setCellStyle(style);//设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if(currentCell != null && !"".equals(currentCell)){
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                int length = currentCell.getStringCellValue().getBytes().length;
                    if (columnWidth < length) {
                    columnWidth = length;
                    }
                    }
                    }
                }
            }
            if(colNum == 0){
            //设置表体第一列的宽度
            sheet.setColumnWidth(colNum, (columnWidth-2) * 60);
            }else{
            //设置表体其他列的宽度
            sheet.setColumnWidth(colNum, (columnWidth+4) * 400);
            }
        }
return workbook;
}
/**
* 表头样式
* @param workbook
* @return
*/
public static HSSFCellStyle getTopStyle(HSSFWorkbook workbook) {
 // 设置字体
 HSSFFont font = workbook.createFont();
 //设置字体大小
 font.setFontHeightInPoints((short)11);
 //字体加粗
 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 //设置字体名字 
 font.setFontName("Courier New");
 //设置样式; 
 HSSFCellStyle style = workbook.createCellStyle();
 //设置底边框; 
 style.setBorderBottom((short)0);
 //设置左边框;   
 style.setBorderLeft((short)0);
 //设置右边框; 
 style.setBorderRight((short)0);
 //设置顶边框; 
 style.setBorderTop((short)0);
 //在样式用应用设置的字体;  
 style.setFont(font);
 //设置自动换行; 
 style.setWrapText(true);
 //设置水平对齐的样式为居中对齐;  
 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
 //设置垂直对齐的样式为居中对齐; 
 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
 return style;
}
/**
* 表体样式
* @param workbook
* @return
*/
public static HSSFCellStyle getCommonStyle(HSSFWorkbook workbook) {
 // 设置字体
 HSSFFont font = workbook.createFont();
 //设置字体大小
 font.setFontHeightInPoints((short)11);
 //字体加粗
 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 //设置字体名字 
 font.setFontName("Courier New");
 //设置样式; 
 HSSFCellStyle style = workbook.createCellStyle();
 //设置底边框; 
 style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
 //设置底边框颜色;  
 style.setBottomBorderColor(HSSFColor.BLACK.index);
 //设置左边框;   
 style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 //设置左边框颜色; 
 style.setLeftBorderColor(HSSFColor.BLACK.index);
 //设置右边框; 
 style.setBorderRight(HSSFCellStyle.BORDER_THIN);
 //设置右边框颜色; 
 style.setRightBorderColor(HSSFColor.BLACK.index);
 //设置顶边框; 
 style.setBorderTop(HSSFCellStyle.BORDER_THIN);
 //设置顶边框颜色;  
 style.setTopBorderColor(HSSFColor.BLACK.index);
 //在样式用应用设置的字体;  
 style.setFont(font);
 //设置自动换行; 
 style.setWrapText(false);
 //设置水平对齐的样式为居中对齐;  
 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
 //设置垂直对齐的样式为居中对齐; 
 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
 return style;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值