[Tex/LaTex] Importing Tabular Cells from Text File

inputtables

Suppose I want to build a table which looks as follows:

\begin{tabular}{ccc}  
 1.23 & 2.98 & Apple \\  
-3.78 & 4.01 & Banana \\  
\end{tabular}

However, the numbers in the table are given in a separate text file, say "file.txt", with the content

1.23 & 2.98
-3.78 & 4.01

Is there a simple way to input the cells from "file.txt" into a larger table? I tried

\begin{tabular}{ccc}
\input{file.txt} & \multirow{2}{*}{Apple \\ Banana} \\
\end{tabular}

but this fails (unsurprisingly). I also tried to use minipages – this works in the above toy example but fails in more realistic ones (most importantly, I could not align inputs from different files).

Any comments/suggestions welcome!

EDIT Here's a MWE. The file "file.txt" is as mentioned above. "file2.txt" has the following contents:

1.23 & 2.98 \\
-3.78 & 4.01 \\

(obviously, both "file.txt" and "file2.txt" should be saved in the directory of the tex file). Code for MWE:

\documentclass{article}
\usepackage{multirow}

\begin{document}

% Approach using minipage (works, but looks ugly)
\begin{minipage}{0.4\textwidth}
\begin{tabular}{cc}
\input{file2.txt} 
\end{tabular}
\end{minipage}
\begin{minipage}{0.2\textwidth}
\begin{tabular}{c}
Apple \\ Banana
\end{tabular}
\end{minipage}

% Approach mentioned above (fails)
\begin{tabular}{ccc}
\input{file.txt} & \multirow{2}{*}{Apple \\ Banana} \\
\end{tabular}

\end{document}

Best Answer

You can define \preparetable macro which prepares data for the table:

\preparetable {file.txt} {Apple, Banana}

and then use this in the table environment:

\begin{tabular}{ccc} \usetable \end{tabular}

The whole example follows:

\documentclass{article}      

\newread\infile
\def\preparetable#1#2{\bgroup \openin\infile=#1
   \let\\=\relax \gdef\usetable{}\preparetableA #2,,}
\def\preparetableA #1,{\if,#1,\egroup \closein\infile \else \read\infile to\tmp
  \xdef\usetable{\usetable \tmp & #1 \\}\expandafter\preparetableA\fi}

\begin{document}

\preparetable {file.txt} {Apple, Banana}
\begin{tabular}{ccc} \usetable \end{tabular}

\end{document}
Related Question