首先我要说,我完全是新手,刚开始接触开发领域。
我尝试生成一个包含乘法表、有边框并设置背景颜色但只针对第一列和第一行的Excel表格。
这里有一个正确的示例: 正确示例
我写了类似下面的代码,但结果文件中有颜色的单元格没有边框 :(
请告诉我如何同时设置背景颜色和边框。
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.awt.image.IndexColorModel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Excel {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("请输入行数: ");
int x = in.nextInt();
System.out.println("请输入列数: ");
int y = in.nextInt();
System.out.println("请输入文件名: ");
String fileName = in.next() + ".xls";
System.out.println("乘法表将被创建在文件 " + fileName + " 中");
createExcelMultiplicationTable(fileName, x, y);
System.out.println("进程执行成功");
}
private static void createExcelMultiplicationTable(String fileName, int x, int y) throws IOException {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("multiplicationTable");
CellStyle backgroundStyle = workbook.createCellStyle();
backgroundStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
backgroundStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
CellStyle borderStyle = workbook.createCellStyle();
borderStyle.setBorderBottom(CellStyle.BORDER_THIN);
borderStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
borderStyle.setBorderLeft(CellStyle.BORDER_THIN);
borderStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
borderStyle.setBorderRight(CellStyle.BORDER_THIN);
borderStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
borderStyle.setBorderTop(CellStyle.BORDER_THIN);
borderStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
for (int i = 1; i <= x; i++) {
Row row = sheet.createRow(i - 1);
for (int j = 1; j <= y; j++) {
Cell cell = row.createCell(j - 1);
cell.setCellValue(i * j);
cell.setCellStyle(borderStyle);
if (cell.getRowIndex() == 0 || cell.getColumnIndex() == 0) {
cell.setCellStyle(backgroundStyle);
}
}
}
FileOutputStream out = new FileOutputStream(fileName);
workbook.write(out);
out.close();
}
}