POI常用操作

最近做到xls编辑、下载的功能,记录下新get到的技能。

1、拷贝sheet。使用场景:xls的以第一个sheet是模板,已经设置好了样式。需要拷贝第一个sheet到其他sheet。

// 克隆第一个模板sheet
for (int index = 1; index < xxList.size(); index++) 
{
      workbook.cloneSheet(0);
}


2、xls的sheet名称不能重复,必需是唯一的,否则就会报异常。可以使用poi的api解决这个问题。

a、获取一个合法的sheet name

String sheetName = WorkbookUtil.createSafeSheetName(meal.getName());

b、获取一个唯一的sheet name,如果重名,加后缀(2),(3),依次递增。

public static String getUniqueSheetName(String srcName, HSSFWorkbook workbook) {
        int uniqueIndex = 2;
        String baseName = srcName;
        int bracketPos = srcName.lastIndexOf('(');
        if (bracketPos > 0 && srcName.endsWith(")")) {
            String suffix = srcName.substring(bracketPos + 1, srcName.length() - ")".length());
            try {
                uniqueIndex = Integer.parseInt(suffix.trim());
                uniqueIndex++;
                baseName=srcName.substring(0, bracketPos).trim();
            } catch (NumberFormatException e) {
                // contents of brackets not numeric
            }
        }
        while (true) {
            // Try and find the next sheet name that is unique
            String index = Integer.toString(uniqueIndex++);
            String name;
            if (baseName.length() + index.length() + 2 < 31) {
                name = baseName + " (" + index + ")";
            } else {
                name = baseName.substring(0, 31 - index.length() - 2) + "(" + index + ")";
            }

            //If the sheet name is unique, then set it otherwise move on to the next number.
            if (workbook.getSheetIndex(name) == -1) {
              return name;
            }
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值