import java.util.Iterator;
import java.util.Map;
import java.util.Set;
+import java.util.TreeMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
BorderStyle.SLANTED_DASH_DOT, "dashed 2pt",
BorderStyle.THICK, "solid 3pt",
BorderStyle.THIN, "dashed 1pt");
+
+ private static final int IDX_TABLE_WIDTH = -2;
+ private static final int IDX_HEADER_COL_WIDTH = -1;
+
@SuppressWarnings({"unchecked"})
private static <K, V> Map<K, V> mapFor(Object... mapping) {
public void printSheet(Sheet sheet) {
ensureOut();
- out.format("<table class=%s>%n", DEFAULTS_CLASS);
- printCols(sheet);
+ Map<Integer, Integer> widths = computeWidths(sheet);
+ int tableWidth = widths.get(IDX_TABLE_WIDTH);
+ out.format("<table class=%s style=\"width:%dpx;\">%n", DEFAULTS_CLASS, tableWidth);
+ printCols(widths);
printSheetContent(sheet);
out.format("</table>%n");
}
+
+ /**
+ * computes the column widths, defined by the sheet.
+ *
+ * @param sheet
+ * @return Map with key: column index; value: column width in pixels
+ * <br>special keys:
+ * <br>{@link #IDX_HEADER_COL_WIDTH} - width of the header column
+ * <br>{@link #IDX_TABLE_WIDTH} - width of the entire table
+ */
+ private Map<Integer, Integer> computeWidths(Sheet sheet) {
+ Map<Integer, Integer> ret = new TreeMap<Integer, Integer>();
+ int tableWidth = 0;
- private void printCols(Sheet sheet) {
- out.format("<col/>%n");
ensureColumnBounds(sheet);
+
+ // compute width of the header column
+ int lastRowNum = sheet.getLastRowNum();
+ int headerCharCount = String.valueOf(lastRowNum).length();
+ int headerColWidth = widthToPixels((headerCharCount + 1) * 256);
+ ret.put(IDX_HEADER_COL_WIDTH, headerColWidth);
+ tableWidth += headerColWidth;
+
+ for (int i = firstColumn; i < endColumn; i++) {
+ int colWidth = poiWidthToPixels(sheet.getColumnWidth(i));
+ ret.put(i, colWidth);
+ tableWidth += colWidth;
+ }
+
+ ret.put(IDX_TABLE_WIDTH, tableWidth);
+ return ret ;
+ }
+
+ /**
+ * Probably platform-specific, but appears to be a close approximation on some systems
+ * @param widthUnits POI's native width unit (twips)
+ * @return the approximate number of pixels for a typical display
+ */
+ protected int widthToPixels(final double widthUnits) {
+ return (int) (Math.round(widthUnits * 9 / 256));
+ }
+
+ private void printCols(Map<Integer, Integer> widths) {
+ int headerColWidth = widths.get(IDX_HEADER_COL_WIDTH);
+ out.format("<col style=\"width:%dpx\"/>%n", headerColWidth);
for (int i = firstColumn; i < endColumn; i++) {
- out.format("<col/>%n");
+ int colWidth = widths.get(i);
+ out.format("<col style=\"width:%dpx;\"/>%n", colWidth);
}
}
}
return "";
}
-}
\ No newline at end of file
+}