62,584
社区成员




class Header extends JTableHeader
{
private int rowHeight = 20;
public Header(int rowHeight)
{
setLayout(new HeaderLayout());
this.rowHeight = rowHeight;
}
@Override
public Dimension getPreferredSize()
{
Dimension d = super.getPreferredSize();
HeaderLayout layout = (HeaderLayout) getLayout();
d.height = layout.getRowCount() * rowHeight;
return d;
}
}
class HeaderCellLabel extends JLabel
{
public HeaderCellLabel(Icon icon, int top, int left, int bottom, int right)
{
this("", icon, top, left, bottom, right);
}
public HeaderCellLabel(String text, Icon icon, int top, int left, int bottom, int right)
{
super(text, icon, JLabel.CENTER);
setBorder(BorderFactory.createMatteBorder(top, left, bottom, right, Color.gray));
// setBorder(BorderFactory.createCompoundBorder(
// BorderFactory.createMatteBorder(0, 0, 1, 1, SystemColor.controlShadow),
// BorderFactory.createMatteBorder(1, 1, 0, 0, SystemColor.controlLtHighlight)));
}
public HeaderCellLabel(String text, int top, int left, int bottom, int right)
{
this(text, null, top, left, bottom, right);
}
}
class HeaderCellConstraints {
public final int x;
public final int y;
public final int colSpan;
public final int rowSpan;
public HeaderCellConstraints(final int x, final int y, final int colSpan, final int rowSpan)
{
this.x = x;
this.y = y;
this.colSpan = colSpan;
this.rowSpan = rowSpan;
}
public HeaderCellConstraints(final int x, final int y, final int colSpan)
{
this(x, y, colSpan, 1);
}
public HeaderCellConstraints(final int x, final int y)
{
this(x, y, 1, 1);
}
}
class HeaderLayout implements LayoutManager2 {
private HashMap<Component, HeaderCellConstraints> compCellMap =
new HashMap<Component, HeaderCellConstraints>();
private int rowCount = 0;
public void addLayoutComponent(Component comp, Object constraints)
{
if (constraints == null || !(constraints instanceof HeaderCellConstraints)) {
return;
}
HeaderCellConstraints cell = (HeaderCellConstraints) constraints;
compCellMap.put(comp, cell);
rowCount = Math.max(rowCount, cell.y + cell.rowSpan);
}
public HeaderCellConstraints getCellConstraint(HeaderCellLabel headerCell) {
return compCellMap.get(headerCell);
}
public int getRowCount()
{
return rowCount;
}
public float getLayoutAlignmentX(Container target)
{
return 0;
}
public float getLayoutAlignmentY(Container target)
{
return 0;
}
public void invalidateLayout(Container target)
{
}
public Dimension maximumLayoutSize(Container target)
{
return preferredLayoutSize(target);
}
public void addLayoutComponent(String name, Component comp)
{
throw new IllegalArgumentException();
}
public void layoutContainer(Container parent)
{
JTableHeader header = (JTableHeader) parent;
JTable table = header.getTable();
TableColumnModel columnModel = table.getColumnModel();
int rowHeight = header.getHeight() / rowCount;
Component[] cellComps = parent.getComponents();
for (Component cellComp : cellComps) {
HeaderCellConstraints cell = compCellMap.get(cellComp);
if (cell == null) {
continue;
}
int cellX = 0;
for (int i = 0; i < cell.x; i++) {
cellX += columnModel.getColumn(i).getWidth();
}
int cellWid = 0;
for (int i = 0; i < cell.colSpan; i++) {
cellWid += columnModel.getColumn(cell.x + i).getWidth();
}
int cellY = rowHeight * cell.y;
int cellHei = rowHeight * cell.rowSpan;
cellComp.setBounds(cellX, cellY, cellWid, cellHei);
}
}
public Dimension minimumLayoutSize(Container parent)
{
return preferredLayoutSize(parent);
}
public Dimension preferredLayoutSize(Container parent)
{
return new Dimension(1,1);
}
public void removeLayoutComponent(Component comp)
{
compCellMap.remove(comp);
rowCount = 0;
for (HeaderCellConstraints cell : compCellMap.values()) {
rowCount = Math.max(rowCount, cell.y + cell.rowSpan);
}
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
//复杂表头的JTable
public class ComplexTableHeader
{
public static void main(String[] args) throws Exception
{
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
final JTable table = new JTable(20, 4) {
@Override
protected JTableHeader createDefaultTableHeader()
{
Header header = new Header(18);
header.add(new HeaderCellLabel("abc", 0, 0, 1, 1), new HeaderCellConstraints(0, 0));
header.add(new HeaderCellLabel("ss", 0, 0, 1, 1), new HeaderCellConstraints(1, 0));
header.add(new HeaderCellLabel("s", 0, 0, 1, 1), new HeaderCellConstraints(2, 0));
header.add(new HeaderCellLabel("dhc", 0, 0, 1, 1), new HeaderCellConstraints(3, 0));
header.add(new HeaderCellLabel("aaaabbbb", 0, 0, 1, 1), new HeaderCellConstraints(0, 1, 3));
header.add(new HeaderCellLabel("abc", 0, 0, 1, 1), new HeaderCellConstraints(0, 2, 1, 2));
header.add(new HeaderCellLabel("ss", 0, 0, 1, 1), new HeaderCellConstraints(1, 2));
header.add(new HeaderCellLabel("ss", 0, 0, 1, 1), new HeaderCellConstraints(1, 3));
header.add(new HeaderCellLabel("s", 0, 0, 1, 1), new HeaderCellConstraints(2, 2));
header.add(new HeaderCellLabel("s", 0, 0, 1, 1), new HeaderCellConstraints(2, 3));
header.add(new HeaderCellLabel("zzz", 0, 0, 1, 1), new HeaderCellConstraints(3, 1, 1, 3));
return header;
}
};
for (int i = 0; i < table.getRowCount(); i++) {
for (int k = 0; k < table.getColumnCount(); k++) {
table.setValueAt("Cell(" + i + ", " + k + ")", i, k);
}
}
JScrollPane sp = new JScrollPane(table);
JPanel p = new JPanel(new BorderLayout(0, 10));
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
p.add(sp);
JButton exportBtn = new JButton("Export");
exportBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
exportTable(table);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
p.add(exportBtn, BorderLayout.SOUTH);
JFrame f = new JFrame();
f.getContentPane().add(p, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
protected static void exportTable(JTable table) throws IOException {
// create a new file
FileOutputStream out = new FileOutputStream("workbook.xls");
// create a new workbook
HSSFWorkbook wb = new HSSFWorkbook();
// create a new sheet
HSSFSheet s = wb.createSheet();
// declare a row object reference
HSSFRow r = null;
// declare a cell object reference
HSSFCell c = null;
// create 3 cell styles
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFCellStyle headerCellStyle = wb.createCellStyle();
// create font object
HSSFFont headerCellFont = wb.createFont();
//set font 2 to 10 point type
headerCellFont.setFontHeightInPoints((short) 10);
//make it bold
headerCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
headerCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerCellStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
headerCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headerCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// set the font
headerCellStyle.setFont(headerCellFont);
// set the sheet name in Unicode
wb.setSheetName(0, "测试");
short rowOffset = 1;
short colOffset = 1;
Header header = (Header) table.getTableHeader();
HeaderLayout layout = (HeaderLayout) header.getLayout();
HSSFRow[] rows = new HSSFRow[layout.getRowCount()];
for (int i = 0; i < layout.getRowCount(); i++) {
rows[i] = s.createRow(i + rowOffset);
}
int headerCellCount = header.getComponentCount();
for (int i = 0; i < headerCellCount; i++) {
if (header.getComponent(i) instanceof HeaderCellLabel) {
HeaderCellLabel headerCell = (HeaderCellLabel) header.getComponent(i);
String headerCellValue = headerCell.getText();
HeaderCellConstraints constraint = layout.getCellConstraint(headerCell);
if (constraint.rowSpan > 1 || constraint.colSpan > 1) {
s.addMergedRegion(new Region(
constraint.y + rowOffset,
(short) (constraint.x + colOffset),
constraint.y + constraint.rowSpan + rowOffset - 1,
(short) (constraint.x + constraint.colSpan + colOffset - 1)));
for (int m = 0; m < constraint.colSpan; m++) {
for (int n = 0; n < constraint.rowSpan; n++) {
rows[constraint.y + n].createCell(
(short) (constraint.x + colOffset + m)).setCellStyle(headerCellStyle);
}
}
}
c = rows[constraint.y].createCell((short) (constraint.x + colOffset));
c.setCellStyle(headerCellStyle);
c.setCellValue(new HSSFRichTextString(headerCellValue));
}
}
rowOffset += (short) layout.getRowCount();
for (short row = 0; row < table.getRowCount(); row++)
{
// create a row
r = s.createRow(row + rowOffset);
// create 10 cells (0-9) (the += 2 becomes apparent later
for (short column = (short) 0; column < table.getColumnCount(); column ++)
{
// create a numeric cell
c = r.createCell((short)(column + colOffset));
Object cellValue = table.getValueAt(row, column);
c.setCellStyle(cellStyle);
c.setCellValue( new HSSFRichTextString(cellValue == null ? "" : cellValue.toString()) );
// make this column a bit wider
s.setColumnWidth((short)(column + colOffset), (short) (15 * 256));
}
}
// write the workbook to the output stream
// close our file (don't blow out our file handles
wb.write(out);
out.close();
}
}