Java:从Excel读取int作为字符串返回十进制?
我正在尝试从 Excel 文件中读取一个整数,如下所示:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String myExcel = "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ="";" +
"DriverID=22;READONLY=false";
con = DriverManager.getConnection(myExcel);
stmt = con.createStatement();
rs = stmt.executeQuery("select * from [users$] where userid=" + userid);
while(rs.next()) {
System.out.println(rs.getString("phone"));
}
问题:如果我们假设 Excel 工作表中的电话 = 123456,则 rs.getString("phone") 返回带小数 0 的整数,例如“123456.0”
我知道我可以使用 rs.getInt("phone") 代替,但电话有时会有“+”、“#”等字符。
使用 rs.getString 获取整数的最佳方法是什么?
I'm trying to read an integer from an Excel file like this:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String myExcel = "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ="";" +
"DriverID=22;READONLY=false";
con = DriverManager.getConnection(myExcel);
stmt = con.createStatement();
rs = stmt.executeQuery("select * from [users$] where userid=" + userid);
while(rs.next()) {
System.out.println(rs.getString("phone"));
}
The problem: if we assume the phone in the Excel sheet = 123456, rs.getString("phone") returns the integer with decimal 0, like this "123456.0"
I know I can use rs.getInt("phone") instead, but the phone sometimes have characters like "+","#",etc.
What's the best way to use rs.getString to get integer as it is??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试添加
到连接字符串。这指示驱动程序将混合数据(不同数据类型的数据)视为文本。
如果它不起作用,请尝试添加
IMEX=1
指令SQL 语句。如果这仍然不起作用,还有以下选项: 使用 Apache POI;将 Excel 工作表转换为 CSV;使用办公自动化显式设置列的数据类型;重新处理该值(即通过应用一些子字符串
操作等)。Try adding
to the connection string. This instructs the driver to treat intermixed data (data of different data types) as text.
If it does not work, try adding the
IMEX=1
instruction to the SQL statement. If this still doesn't work, there are the following options: Use Apache POI; convert the Excel sheet to CSV; use Office automation to explicitly set the column's data type; rework the value (i.e. by applying somesubstring
operation, etc.).您必须将电话号码作为字符串读取,然后对其进行解析以删除不需要的字符。最后,使用
Integer.parseInt(phoneNumberString)
将其转换为int
。You would have to read the phone number as a string and then parse it to get rid of unwanted characters. Finally, convert it to an
int
usingInteger.parseInt(phoneNumberString)
.