Skip to content

Instantly share code, notes, and snippets.

@taichi
Last active February 4, 2023 20:09
Show Gist options
  • Save taichi/6d0333fddec9f312fd317fb51c1619e7 to your computer and use it in GitHub Desktop.
Save taichi/6d0333fddec9f312fd317fb51c1619e7 to your computer and use it in GitHub Desktop.
Excelのシートに配置されたオートシェイプを左上から順番にソートするコード
package com.example.hssf;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFSimpleShape;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
// 参考にしたブログ。https://ohbarye.hatenablog.jp/entry/2014/04/28/100400
public class ShapeSortExample {
class PositionShape {
HSSFSimpleShape shape;
int x;
int y;
PositionShape(HSSFSheet sheet, HSSFSimpleShape shape) {
this.shape = shape;
var anchor = (HSSFClientAnchor) shape.getAnchor();
var column = anchor.getCol1();
if (0 < column) {
for (var i = column; -1 < i; i--) {
x += sheet.getColumnWidth(i);
}
}
x += anchor.getDx1();
var row = anchor.getRow1();
if (0 < row) {
for (var i = row; -1 < i; i--) {
y += sheet.getRow(i).getHeight();
}
}
y += anchor.getDy1();
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public void read(String filename) throws Exception {
try (var fs = new POIFSFileSystem(new File(filename))) {
var book = new HSSFWorkbook(fs);
var sheet = book.getSheet("すごいシート");
var pat = sheet.getDrawingPatriarch();
var list = StreamSupport.stream(pat.spliterator(), false)
.filter(sh -> sh instanceof HSSFSimpleShape)
.map(sh -> (HSSFSimpleShape) sh)
.filter(sh -> sh.getShapeType() == HSSFSimpleShape.OBJECT_TYPE_RECTANGLE)
.map(sh -> new PositionShape(sheet, sh))
.sorted(Comparator.comparing(PositionShape::getY).thenComparing(PositionShape::getX))
.collect(Collectors.toList());
System.out.println(list);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment