17

入力としてヘッダーとデータを受け取り、Excel ファイルを生成する Java プログラムがあります。

ただし、ヘッダー値が長く、列数が多いと、Excel シートが不必要に広くなる傾向があります。

ヘッダーがあるため、最後尾の列の内容を表示するには、右にスクロールする必要があります。

セル内のコンテンツが大きい場合、値 x と言うと、自動折り返しが発生し、行の高さが自動的に調整され、列の幅が固定されるように、これを解決できる方法はありますか。

私が探しているものの大まかなアルゴリズムは次のとおりです。

 if(content.size is more then 50 chars){
       - apply auto wrap with centred text
       - adjust the row height accordingly
       - adjust all the cells in the column accordingly
 }

誰かが私にオンラインで入手可能な例を教えてくれたら.

読んでくれてありがとう!

4

1 に答える 1

64

Cell スタイルでこれを達成できるはずです。表示する例をまとめてみました。

public class SO{
    public static void main(String[] args) {

        try {
            FileInputStream is = new FileInputStream(new File("D:\\Users\\user2777005\\Desktop\\bob.xlsx"));
            XSSFWorkbook wb = new XSSFWorkbook(is);
            String header = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789";
            Sheet sheet = wb.getSheet("Sheet1");
            sheet.setColumnWidth(0, 18000);
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);

            if(header.length() > 50){ //Length of String for my test
                sheet.setColumnWidth(0, 18000); //Set column width, you'll probably want to tweak the second int
                CellStyle style = wb.createCellStyle(); //Create new style
                style.setWrapText(true); //Set wordwrap
                cell.setCellStyle(style); //Apply style to cell
                cell.setCellValue(header); //Write header
            }

            wb.write(new FileOutputStream(new File("D:\\Users\\user2777005\\Desktop\\bob.xlsx")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}       

幸運を!

于 2013-10-30T09:00:02.777 に答える