繁体   English   中英

如何将负数从 Excel 与 PHP 转换

[英]How can I convert a negative number from Excel with PHP

我将带有 php 的“xlsx”文件导入 MySQL 数据库。

在 Excel 中,数字看起来像这样(德国数字格式):2,564.30 或 -2,564.30

我将此字符串转换为数字,以便能够将其作为数字保存在 MySQL 中,如下所示:

floatval (preg_replace("/[-]?[^-0-9\.]/", "", $row[16]))

该数字已导入,但不包括减号。 我只得到正数。

output 总是

2564.30

不幸的是总是没有减号!

我不熟悉正则表达式。

更新

对不起,但没有一个变体工作。

这是 Excel 中的数字: 1

这在 mysql 中: 2

在 mysql 数据库中格式化为:float(12,2) 这里的代码来自 import.php:

 <?php include '../assets/inc/db.php'; include '../assets/inc/db2.php'; include '../assets/inc/SimpleXLSX.php'; require '../vendor/autoload.php'; if(isset($_GET['bvh'])){ $bvh = $_GET['bvh']; }else{ echo "Kein BVH ausgewählt"; } $inputFileType = 'Xlsx'; $inputFileName = './importe/as4u_export.xlsx'; $sheetname = '0001'; /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($column, $row, $worksheetName = '') { // Read rows 1 to 7 and columns A to E only if ($row >= 5 && $row <= 65536) { if (in_array($column,range('A','Q'))) { return true; } } return false; } } /** Create an Instance of our Read Filter **/ $filterSubset = new MyReadFilter(); /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Tell the Reader that we want to use the Read Filter **/ $reader->setReadFilter($filterSubset); /** Load only the rows and columns that match our filter to Spreadsheet **/ $spreadsheet = $reader->load($inputFileName); $data = $spreadsheet->getActivesheet()->toArray(); $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); foreach($data as $row){ $insert_data = array( ':as4u_KOA' => $row[5], ':as4u_KOA_name' => $row[8], ':as4u_text' => $row[14], ':as4u_betrag' => floatval(preg_replace('~^-\K|[^-\d.]~', '', $row[16])), ); $query = "INSERT INTO ww_as4u (as4u_bvh_id, as4u_KOA, as4u_KOA_name, as4u_text, as4u_betrag) VALUES ('$bvh', :as4u_KOA, :as4u_KOA_name, :as4u_text, :as4u_betrag)"; $statement = $conn->prepare($query); $statement->execute($insert_data); }

作为使用正则表达式的替代方法,您还可以使用 PHP 的NumberFormatter class。

$formatter = new NumberFormatter("de-DE", NumberFormatter::DECIMAL);
$formatter->parse("2.564,30");  // Gives 2564.3
$formatter->parse("-2.564,30"); // Gives -2564.3

由于NumberFormatter是 PHP 的Intl (= Internationalization) 扩展的一部分,它可能已安装/启用,也可能尚未安装/启用,具体取决于您的 PHP 版本。

如果它不是现成的,请参阅:

对于NumberFormat本身,请参阅:

您可以使用

preg_replace('~^-\K|[^-\d.]~', '', $row[16])

请参阅正则表达式演示

细节

  • ^-\K - 匹配字符串开头的-并省略匹配
  • | - 或者
  • [^-\d.] - 除- 、`数字和点之外的任何字符。

请参阅PHP 演示

$strs = [' 2,564.30', '-2,564.30'];
print_r(preg_replace('~^-\K|[^-\d.]~', '', $strs));
// => Array( [0] => 2564.30    [1] => -2564.30 )

试试这个:“/[^-0-9.]/”对于正则表达式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM