我使用 PHP 生成了表格(tabu、longtable 等),其中单元格内容可变。有时,列中的所有单元格都是空的,在这种情况下,我会用标题隐藏整列。
这里我们有手动隐藏列的解决方案。是否可以编写任何脚本来自动执行此操作?
最小示例代码:
\documentclass[a4paper]{article}
\begin{document}
\begin{tabular}{c c}
\hline
\textbf{Lp.} & name \\\hline
1 & \\\hline
2 & \\\hline
\end{tabular}
\end{document}
在这种情况下,我想隐藏“名称”列
答案1
\documentclass[a4paper]{article}
\usepackage{array}
% define hidden column type
\newcolumntype{H}{>{\setbox0=\hbox\bgroup}c<{\egroup}@{}}
% counter for non-blanks
\newcounter{ub}
% define character count function
\def\gchar{\let\char= }
\newcount\ccount
\def\cunil{%
\ifx\char\nil \let\next=\relax%
\else%
\let\next=\axchar%
\advance\ccount by 1%
\fi\next
}
\def\axchar{\afterassignment\cunil\gchar}
\def\cchar#1{\edef\xx{#1}\ccount=0 \expandafter\axchar\xx\nil}
\long\def\xc#1{#1\cchar{#1}
\ifnum\ccount>0
\stepcounter{ub}
\fi
}
% define conditional display function
\def\disptab#1{
\ifnum#1>0%
\tablebody{c c}%
\else%
\tablebody{c H}%
\fi
}
% define table structure function
\def\tablebody#1{
\begin{tabular}{#1}
\hline
\textbf{Lp.} & name \\\hline
%%%%%% try removing what is in \xc{} %%%%%%
1 & \xc{} \\\hline
2 & \xc{abc} \\\hline
3 & \xc{} \\\hline
4 & \xc{3.14} \\\hline
5 & \xc{} \\\hline
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{tabular}
}
\begin{document}
% use box to initially render table without displaying it,
% so non-blanks can be counted
\newbox\uvox
\setbox\uvox\hbox{\tablebody{c c}}
% display table
\disptab{\theub}
\end{document}
请注意,要隐藏的列中的每个单元格都应被括起来\xc{}
才能正常工作。