这个包裹datatool
让我有些头疼货币类型字段。
我的数据是test.csv
从 Excel 导出的文件,没有标题:
a,"$100,090.06 ","$107,578.03 ",0.129565278
b,"$267,697.13 ","$72,463.54 ",0.087442318
c,"$761,314.81 ","$192,210.83 ",0.231820008
some text
some text2
我想 (1) 添加总计对于某些列;以及 (2)圆形的数字:
Label Amount1 Amount2 Percent
----------------------------------------
a $100,090 $107,578 13%
b $267,697 $72,464 9%
c $761,315 $192,211 23%
----------------------------------------
Total: $1,129,102 45%
这是我的代码:
\documentclass[a4paper, 11pt]{article}
\usepackage{datatool}
\begin{document}
\DTLloadrawdb[noheader,headers={label,Amount1,Amount2,\%},keys={A,B,C,D}]{myDB}{test.csv}
Displaying the table:\\
\DTLdisplaydb{myDB} \\
Operating the table:\\
\def\totalAmount{0}
\def\totalPercent{0} %initializing totalAmount and totalPercent to 0
\begin{tabular}{r|ll|r}
label & Amount1 & Amount2 & Percent
\DTLforeach[\value{DTLrowi}<3]{myDB}{\aa=A,\bb=B,\cc=C,\dd=D}{
\\
\aa & \bb & \cc &
\DTLmul{\dd}{\dd}{100}\DTLround{\dd}{\dd}{0}\dd\% %formatting the percent column
\DTLgadd{\totalPercent}{\dd}{\totalPercent} %cumulating percentages
\DTLgadd{\totalAmount}{\bb}{\totalAmount} %cumulating Amount <- THIS LINE DOES NOT WORK (when removing it, the code does partially what I want), probably because \bb is not seen as real
} \\ \hline
Total & \totalAmount & & \totalPercent\%
\end{tabular}
\end{document}
我想我的失败是因为\bb
和\cc
都是货币而不是真实的。
答案1
问题在于 CSV 货币值中的尾随空格。由于这些空格,数字被视为字符串,并且从货币到十进制的内部转换失败。因此,对于以下 CSV:
a,"$100,090.06","$107,578.03",0.129565278
b,"$267,697.13","$72,463.54",0.087442318
c,"$761,314.81","$192,210.83",0.231820008
some text
some text2
您的文档可以正常工作。请注意,为了将值视为货币,您需要在定义时先将总计设置为货币。
我还对您设置表格的方式做了一些更改。\\
我没有在每行的开头使用,而是在\\
标题行应该出现的位置添加了,然后使用\DTLiffirstrow
在第一行中消除了它。虽然这在您的特定示例中似乎没有什么不同,但这是一个好习惯,因为在更复杂的示例中,它可能会导致问题。我还删除了表格主体中影响间距的一些额外空格。在表格单元格中执行计算时,最好以 结束宏以%
确保没有多余的空格。
\documentclass{article}
\usepackage{datatool}
\begin{document}
\DTLloadrawdb[noheader,headers={label,Amount1,Amount2,\%},keys={A,B,C,D}]{myDB}{test.csv}
Displaying the table:
\DTLdisplaydb{myDB}
Operating the table:
\def\totalAmount{\$0} % make this a currency
\def\totalPercent{0} %initializing totalAmount and totalPercent to 0
\def\tmp{}
\begin{tabular}{r|rr|r@{}}
label & Amount1 & Amount2 & Percent\\% table newline added here
\DTLforeach[\value{DTLrowi}<3]{myDB}{\aa=A,\bb=B,\cc=C,\dd=D}{%
\DTLiffirstrow{}{\\}
\aa & \bb & \cc &
\DTLmul{\dd}{\dd}{100}\DTLround{\dd}{\dd}{0}\dd\%%formatting the percent column (space removed here)
\DTLgadd{\totalPercent}{\dd}{\totalPercent}%cumulating percentages (space removed here)
\DTLgadd{\totalAmount}{\bb}{\totalAmount}% adding column B (space removed here)
}\\\hline
Total & \totalAmount & &\totalPercent\%
\end{tabular}
\end{document}