[英]How to get Excel sheet size
我需要知道我的工作表將在每一頁上打印多少行(在 PDF 轉換之后)。
我希望計算每一行的大小並將其與頂部和底部邊距相加來計算出來。
示例:頂部和邊距 - 1 個單位,10 行 - 10 個單位。 A4 適合 10 個單位 => 第一頁將包含 8 行(8 個單位 + 1 個上邊距 + 1 個下邊距)。
實際上,我還沒有找到大小與頁面上的行數之間的精確關聯。 我已經在 real.xlsx 上試過了:將所有單位轉換為英寸,但即使超過 A4 頁面大小也可能出現行。
有沒有一種合適的方法來查找頁面上的行數?
如果您使用XSSFSheet
,那么您可以使用sheet.getLastRow()
,如果您使用其他的,則使用sheet.getPhysicalNumberOfRows()
。 Sheet 接口的所有實現都有這個。
我想出了一個解決方案,但也許不是 100% 萬無一失。 單擊視圖 -> 分頁視圖時,Excel 將顯示自己的自動分頁符(虛線)。 我在某處發現 Apache POI 在依賴於頁面格式時無法檢測到這些分頁符,換句話說,它不知道您想要的“頁面”的大小。 我試圖讓它檢測到它,但我沒有成功。
但是,這是我的方法和解決方案:
try {
FileInputStream file=new FileInputStream(pathToFile);
XSSFWorkbook wb=new XSSFWorkbook(file);
XSSFSheet sheet0=wb.getSheetAt(0);
float sizeOfPage=0;
for(int i =0 ; i<end; i++) { //here end should be equal to the last row before
//the automatic page break gets inserted
sizeOfPage=sizeOfPage + sheet0.getRow(i).getHeightInPoints();
}
System.out.println(sizeOfPage); //this is the value you need to get
//calculated
wb.close();
file.close();
}
catch (IOException e) {
}
float length=0; //the length of the whole document
int i =0;
while(i<sheet0MakeQuotationMod.getLastRowNum()-1) { //note that the indexing is
//different in the excel and
//the code, I had trouble
//getting this working....
length=length + sheet0MakeQuotationMod.getRow(i).getHeightInPoints();
i++;
}
float lengthFull=length
int counter=0;
while(length>=sizeOfPage) { //to see how many pages
length/=sizeOfPage;
counter++;
}
double spaceLeft=lengthFull-(sizeOfPage*counter); //to see how much space is left
//on the last page
if(spaceLeft<spaceINeed) { //if this holds, it means that the part I want to be on
//the same page would get separated. I calculated this
//with the same code as above.
//this row break is being applied where I want the segment to be separated
//so that the segment gets shifted to the next page.
sheet0MakeQuotationMod.setRowBreak(indexWhereIWantItToBeSeparated);
}
希望這可以幫助。 請詢問是否有不清楚的地方,我會盡力澄清::)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.