我正在创建一个用于将文档导出为 excel 的脚本。
如何通过合并几个单元格来获得像“姓名:马克出生日期: 11-11-2014”这样的单元格值?
我正在创建一个用于将文档导出为 excel 的脚本。
如何通过合并几个单元格来获得像“姓名:马克出生日期: 11-11-2014”这样的单元格值?
您需要做的是为您的单元格创建一个RichTextString。这是将不同格式/样式应用于同一单元格的不同部分以在 Excel 中显示的方式
您将需要查看POI“使用富文本”示例以了解有关如何使用它的更多信息,但从广义上讲,它类似于
Cell cell = row.createCell(1);
RichTextString rt = new XSSFRichTextString("The quick brown fox");
Font font1 = wb.createFont();
font1.setBoldWeight(Font.BOLDWEIGHT_BOLD);
rt.applyFont(0, 10, font1);
Font font2 = wb.createFont();
font2.setItalic(true);
font2.setUnderline(XSSFFont.U_DOUBLE);
rt.applyFont(10, 19, font2);
Font font3 = wb.createFont();
font3.setBoldWeight(Font.BOLDWEIGHT_NORMAL);
rt.append(" Jumped over the lazy dog", font3);
cell.setCellValue(rt);
这应该会给你一个混合了粗体、斜体+下划线和正常的单元格
我为此创建了一个简短的完整示例。
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class RichTextTest {
public static void main(String[] args) {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
RichTextString richString = new XSSFRichTextString( "Name: Mark DOB: 11-11-2014" );
//^0 ^4 ^11^14
Font fontBold = wb.createFont();
//fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD);
fontBold.setBold(true);
richString.applyFont( 0, 4, fontBold );
richString.applyFont( 11, 14, fontBold );
cell.setCellValue(richString);
try {
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}
如需进一步阅读,请参阅文档。
如何创建工作簿、工作表和单元格: http: //poi.apache.org/spreadsheet/quick-guide.html#CreateCells
如何使用富文本:https ://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFRichTextString.html
字体界面:https ://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Font.html
你试过使用JXLS吗?
使用 xls 模板,您可以从 Excel 读取和写入数据。它的使用非常简单。