A hacky way of doing it, but the following should work in most cases. \myheader takes:
- one optional argument specifying the alignment where
r right-aligns, c centres, and everything else left-aligns.
- After that optional argument follows a mandatory argument containing the contents of the header of the first column.
- After that there is an optional argument that needs to be entered as
[<alignment>,<width>], where <alignment> again is r for right-alignment, c for centred or j for justified and everything else is left-aligned with fixed <width>. If the optional argument is not given, the content is left aligned, but without fixed width.
- And finally the contents of the second column header
Code:
\documentclass[]{article}
\makeatletter
\newcommand\myStrCMP[2]
{%
\bgroup
\def\tmpa{#1}%
\def\tmpb{#2}%
\ifx\tmpa\tmpb
\egroup
\expandafter\@firstoftwo
\else
\egroup
\expandafter\@secondoftwo
\fi
}
\newcommand\myheader[2][l]
{%
\myStrCMP{#1}{c}{\hfill#2\hfill}
{%
\myStrCMP{#1}{r}{\hfill#2}{#2\hfill}%
}
\myheader@i
}
\def\myheader@i%
{%
\@ifnextchar[
{\myheader@ii}
{\myheader@iii}%
}
\long\def\myheader@ii[#1,#2]#3%
{%
\myStrCMP{#1}{r}
{\myheader@iii{\parbox{\dimexpr#2-2\tabcolsep\relax}{\raggedleft#3}}}
{%
\myStrCMP{#1}{c}
{%
\myheader@iii
{%
\parbox
{\dimexpr#2-2\tabcolsep\relax}{\centering#3}%
}%
}
{%
\myStrCMP{#1}{j}
{%
\myheader@iii{\parbox{\dimexpr#2-2\tabcolsep\relax}{#3}}%
}
{%
\myheader@iii
{\parbox{\dimexpr#2-2\tabcolsep\relax}{\raggedright#3}}%
}
}%
}%
}
\newcommand\myheader@iii[1]
{%
\rlap{\hskip2\tabcolsep#1}%
}
\makeatother
\begin{document}
\begin{tabular}[]{|l|@{\hspace{5em}}|}
\hline
\myheader{1col}{2col}\\
\hline
Abc is longer than header\\
\hline
B\\
\hline
\end{tabular}
\begin{tabular}[]{|l|@{\hspace{5em}}|}
\hline
\myheader[c]{1col}[c,5em]{2col}\\
\hline
Abc is longer than header\\
\hline
B\\
\hline
\end{tabular}
\begin{tabular}[]{|l|@{\hspace{5em}}|}
\hline
\myheader[r]{1col}[r,5em]{2col}\\
\hline
Abc is longer than header\\
\hline
B\\
\hline
\end{tabular}
\begin{tabular}[]{|l|@{\hspace{5em}}|}
\hline
\myheader[l]{1col}[l,5em]{2col with long header}\\
\hline
Abc is longer than header\\
\hline
B\\
\hline
\end{tabular}
\end{document}
Result:
