写一个java 动态生成excel表头的代码
时间: 2023-06-05 14:08:09 浏览: 107
好的,我可以帮你生成动态的Excel表头。你可以使用Apache POI这个Java库来实现。以下是一个Java代码示例:
```java
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class ExcelGenerator {
public static void main(String[] args) {
List<String> headers = new ArrayList<>();
headers.add("ID");
headers.add("Name");
headers.add("Email");
headers.add("Phone");
// Create a new workbook
Workbook workbook = new HSSFWorkbook();
// Create a new sheet
Sheet sheet = workbook.createSheet("Sheet1");
// Create a new row for the header
Row headerRow = sheet.createRow(0);
// Create a cell style for the header
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// Set the column width for each column
sheet.setColumnWidth(0, 10000);
sheet.setColumnWidth(1, 10000);
sheet.setColumnWidth(2, 15000);
sheet.setColumnWidth(3, 10000);
// Generate the header cells dynamically
for (int i = 0; i < headers.size(); i++) {
Row currentRow = headerRow;
int currentColumn = i;
// Merge cells for the header
sheet.addMergedRegion(new CellRangeAddress(0, 1, currentColumn, currentColumn));
// Create the header cell
Row row = sheet.getRow(0);
if (row == null) {
row = sheet.createRow(0);
}
row.setHeight((short) 800);
Cell headerCell = row.createCell(currentColumn);
headerCell.setCellValue(headers.get(i));
headerCell.setCellStyle(headerCellStyle);
// Create the second row of the header
Row secondRow = sheet.getRow(1);
if (secondRow == null) {
secondRow = sheet.createRow(1);
}
// Set the data type for the header cell
headerCell.setCellType(CellType.STRING);
// Autofit the column width to fit the header text
sheet.autoSizeColumn(i);
}
try {
// Save the workbook to an OutputStream
OutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码将生成一个包含动态表头的Excel文件,并使用Apache POI库进行操作。你可以根据需要修改列的数量和列标题,以生成任意数量列的动态表头。
阅读全文