ouble getLength(String s) { double valueLength = 0; if (s == null) { return 0; } String chinese = "[\u4e00-\u9fa5]"; // 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 for (int i = 0; i < s.length(); i++) { // 获取一个字符 String temp = s.substring(i, i + 1); // 判断是否为中文字符 if (temp.matches(chinese)) { // 中文字符长度为2 valueLength += 2; } else { // 其他字符长度为1 valueLength += 1; } } // 进位取整 return Math.ceil(valueLength); }
/** * 根据字符串长度获取行高 * * @param str * @return */ public static Float getRowHeight(String str) {
Integer lineCount = (int) (getLength(str) / 64) + 1; if (str.contains("\n")) { Integer tempLineCount = 1; String[] lines = str.split("\n"); for (String line : lines) { Integer everyLineCount = (int) (getLength(line) / 64) + 1; tempLineCount += everyLineCount; } lineCount = lineCount >= tempLineCount ? lineCount : tempLineCount; } Float rowHeight = (float) (lineCount * 20); return rowHeight; }
你需要先获取抓取的字符串的长度,然后通过这个方法计算行高,再将excel需要填充的该行用Java代码设置行高(行高单位是像素),但是如果出现我上面说的字段内容无故中间部分换行,那么你获取的行高就会不足,这个时候你需要改动这个地方----->>>>Float rowHeight = (float) (lineCount * X); x的值一定要设置的大一行,以防出现这种情况!
|