最近做到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;
}
}
}