从excel文件-Java-Swing读取数字
我创建了一个工具,可以上传并从excel文件中获取一些数字从excel文件-Java-Swing读取数字,java,swing,apache-poi,Java,Swing,Apache Poi,我创建了一个工具,可以上传并从excel文件中获取一些数字 public static void main( String[] args ) throws Exception { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { App.file = fc
public static void main( String[] args ) throws Exception {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
App.file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("Opening: " + App.file.getName() + ".");
} else {
System.out.println("Open command cancelled by user.");
}
workbook = Workbook.getWorkbook(App.file);
Sheet sheet = workbook.getSheet(1);
Cell cell1 = sheet.getCell(4, 27);
System.out.println(cell1.getContents());
Cell cell2 = sheet.getCell(4, 28);
System.out.println(cell11.getContents());
App.eStop = false;
int i = 0 ;
while (App.eStop == false) {
try {
cell3 = sheet.getCell(9, i);
System.out.println(cell3.getContents());
} catch (Exception e) {
App.eStop = true;
};
i++;
}
System.out.println("done");
我使用下面的命令将这些值粘贴到其他工具上
psess.GetPS().SendKeys(cell1.getContents(), 8, 18);
excel文件中的所有值都是数字。
有时我会得到十进制数(比如2.02)
因为我无法更改excel文件,所以可以告诉我的应用程序忽略.02,只保留2,例如?你尝试过Math.round()吗?或者新的BigDecimal(cell3.getContents()).setScale(1)?(如果要保留第一个数字)如果Excel文件为要读取的单元格设置了正确的格式,则可以尝试应用该格式,从而以Excel显示的格式获取值 例如,参见以下文件中的示例:
谢谢你的帮助 最后,我用下面的方法解决了我的问题:
Cell cell4 = sheet.getCell(3, 7);
String number3 = cell4.getContents().split("\\.")[0].replaceAll("\\,","");
System.out.println(number3);
读取值并将其解析为int或使用Formatter删除小数抱歉,因为我是新手,您的意思是替换此psess.GetPS().SendKeys(cell1.getContents(),8,18);对于这个:BigDecimal(cell3.getContents()).setScale(1)?是的,类似这样。请在你想要的数字后面打一圈。请描述一下你的答案。
Cell cell4 = sheet.getCell(3, 7);
String number3 = cell4.getContents().split("\\.")[0].replaceAll("\\,","");
System.out.println(number3);
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.math.BigDecimal;
Row currentRow = rowIterator.next();
currentRow.getCell(4).setCellType(XSSFCell.CELL_TYPE_NUMERIC);
Double doubleValue = currentRow.getCell(4).getNumericCellValue();
BigDecimal bd = new BigDecimal(doubleValue.toString());
long lonVal = bd.longValue();
String actualNumber = Long.toString(lonVal).trim();