我有一个名为“data.csv”的 csv 文件,其中包含以下数据:
1,2,3
4,5,6
我正在使用 Latex 编写下表\csvreader
:
\begin{table}
\centering
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\csvreader[
no head,
late after line=\\,
late after last line=,
]{data.csv}{}{\csvcoli & \csvcolii & \csvcoliii} \\
\hline
\end{tabular}
\end{table}
但是,我不想手动输入,而是\csvcoli & \csvcolii & \csvcoliii
想\csvreader
通过 for 循环来实现。所以我写了以下代码:
\newcommand{\mycommand}[1]{
\foreach \i in {1,...,#1}{
\ifnum\i > 1
\&
\fi
\csname csvcol\romannumeral\i\endcsname
}
}
\begin{table}
\centering
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\csvreader[
no head,
late after line=\\,
late after last line=,
]{data.csv}{}{\mycommand{3}} \\
\hline
\end{tabular}
\end{table}
你能帮帮我吗?提前谢谢了。
答案1
使用该软件包可以方便地完成此readarray
操作。
\begin{filecontents*}[overwrite]{data.csv}
1,2,3
4,5,6
\end{filecontents*}
\documentclass{article}
\usepackage{readarray}
\readarraysepchar{,}
\readdef{data.csv}\mydata
\readarray*\mydata\myarray[-,\ncols]
\renewcommand\typesetrowsepchar{\\}
\renewcommand\typesetcolsepchar{&}
\begin{document}
\begin{table}
\centering
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\typesetarray\myarray\\
\hline
\end{tabular}
\end{table}
\end{document}
答案2
csvsimple-l3
提供\csvlinetotablerow
您想要的功能。csvsimple-l3
可以加载\usepackage[l3]{csvsimple}
或usepackage{csvsimple-l3}
\begin{filecontents*}[noheader,overwrite]{data.csv}
1,2,3
4,5,6
\end{filecontents*}
\documentclass{article}
\usepackage{csvsimple-l3}
\begin{document}
Original, using \verb|\csvcoli & \csvcolii & \csvcoliii|\par
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\csvreader[
no head,
late after line=\\,
late after last line=,
]{data.csv}{}{\csvcoli & \csvcolii & \csvcoliii} \\
\hline
\end{tabular}
\medskip
Using \verb|\csvlinetotablerow|\par
\begin{tabular}{|c|c|c|}
\hline
Sue & Karl & Tim \\
\hline
\csvreader[
no head,
late after line=\\,
late after last line=,
]{data.csv}{}{\csvlinetotablerow} \\
\hline
\end{tabular}
\medskip
Using \verb|\csvautotabular|\par
\csvautotabular*[
table head={\hline Sue & Karl & Tim \\ \hline}
]{data.csv}
\end{document}