루프를 사용하여 테이블 생성

루프를 사용하여 테이블 생성

목표는 모든 행을 차례로 조판할 필요 없이 패키지 \foreach에서 제공하는 명령 과 같은 일종의 루프를 사용하여 다음 테이블을 생성하는 것입니다.pgffor

여기에 이미지 설명을 입력하세요

MWE

\documentclass{article}
\usepackage{array,booktabs,pgffor}
\newcommand{\myhrule}{\rule{1cm}{0.5pt}}
\begin{document}
%
\begin{tabular}{p{0.5cm}*{3}{>{\centering\arraybackslash}p{2cm}}}\toprule
  \(i\) & \(m\) & \(P\)  & \(y_{m}\) \\\midrule
  1&  \myhrule   &  \myhrule& \myhrule\\
  2&  \myhrule   &  \myhrule& \myhrule\\
  3&  \myhrule   &  \myhrule&\myhrule\\
  4&  \myhrule   &  \myhrule&\myhrule\\
  5&  \myhrule   &  \myhrule&\myhrule\\
  6&  \myhrule   &  \myhrule& \myhrule\\
  7&  \myhrule   &  \myhrule& \myhrule\\
  8&  \myhrule   &  \myhrule&\myhrule\\
  9&  \myhrule   &  \myhrule&\myhrule\\\bottomrule

\end{tabular}

\noindent
\foreach \i in {1,...,9}{\i \hspace{1cm} \myhrule \hspace{1cm} \myhrule\hspace{1cm} \myhrule \\}

%or 

\noindent
\foreach \i in {1,...,9}{\i \foreach \j in {1,...,3} {\hspace{1cm} \myhrule}\\}
%
\end{document}

답변1

간단한 솔루션pgfplotstable

를 사용하여 원하는 행 수의 테이블을 처음부터 만든 \pgfplotstablenew다음 \pgfplotstabletypeset.

으로 설정된 열 스타일은 \pgfplotstableset완전히 사용자 정의할 수 있습니다.

\documentclass{article}
\usepackage{array,booktabs,pgffor}
\newcommand{\myhrule}{\rule{1cm}{0.5pt}}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.14}
\begin{document}
%set the columns style and content
\pgfplotstableset{
    create on use/new/.style={create col/expr={\pgfplotstablerow+1}},
    columns/new/.style={column name={\(i\)},column type={p{0.5cm}}},
    create on use/emme/.style={create col/set={\myhrule}},
    columns/emme/.style={column name={\(m\)},string type, column type={>{\centering\arraybackslash}p{2cm}}},
    create on use/pi/.style={create col/copy={emme}},
    columns/pi/.style={column name={\(P\)},string type, column type={>{\centering\arraybackslash}p{2cm}}},
    create on use/yup/.style={create col/copy={emme}},
    columns/yup/.style={column name={\(y_{m}\)},string type, column type={>{\centering\arraybackslash}p{2cm}}},
    }
%create a table with the desidered number of rows
\pgfplotstablenew[
    columns={new, emme, pi, yup}
    ]{9}% <--- put here the number of rows you like
    \loadedtable
%display the table
\pgfplotstabletypeset[
    every last row/.style={after row=\bottomrule},
    every head row/.style={before row=\toprule,after row=\midrule},
    ]\loadedtable

\end{document}

여기에 이미지 설명을 입력하세요

답변2

다음은 LuaLaTeX 기반 답변입니다. 패키지는 필요 없습니다 pgffor.

여기에 이미지 설명을 입력하세요

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{array,booktabs}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\newcommand{\myhrule}{\rule{1cm}{0.5pt}}

\usepackage{luacode}
\begin{luacode}
function print_line (i)
  tex.sprint(i.."&\\myhrule&\\myhrule&\\myhrule\\\\")
end
\end{luacode}

\begin{document}
\begin{tabular}{@{} p{0.5cm} *{3}{C{2cm}} @{}}
\toprule
\(i\) & \(m\) & \(P\)  & \(y_{m}\) \\
\midrule
\directlua{ for i = 1 , 10 do print_line ( i ) end }
\bottomrule
\end{tabular}
\end{document}

부록: Lua 코드를 일반화하여 줄 바꿈을 강제하기 전에 항상 복사본이 J아닌 인쇄하도록 하고 싶다고 가정해 보겠습니다 . 예 를 들어 , 당신이 해야 할 일은 (a) 교체하는 것뿐입니다.3&\\myhruleJ=5

function print_line (i)
  tex.sprint(i.."&\\myhrule&\\myhrule&\\myhrule\\\\")
end

~와 함께

function print_line (i,J)
  tex.sprint(i)
  for j=1,J do tex.sprint("&\\myhrule") end
  tex.sprint("\\\\")
end

(b) 함수 호출을 변경합니다.

print_line ( i )

에게

print_line ( i , 5)

\directlua환경 의 후속 지시문의 인수에서 tabular.

답변3

첫 번째 구현:

\documentclass{article}
\usepackage{array,booktabs}
\usepackage{xparse}

\newcommand{\myhrule}{\rule{1cm}{0.4pt}}

\ExplSyntaxOn

\NewDocumentCommand{\makeruledtabular}{mm}
 {% #1 = number of rows, #2 = header
  \begin{tabular}{r w{c}{2cm} w{c}{2cm} @{}}
  \toprule
  #2 \\
  \midrule
  \int_step_function:nN {#1} \__hafid_ruledtabular_line:n
  \bottomrule
  \end{tabular}
 }

\cs_new_protected:Nn \__hafid_ruledtabular_line:n
 {
  #1 & \myhrule & \myhrule \\
 }

\ExplSyntaxOff

\begin{document}

\makeruledtabular{10}{\multicolumn{1}{c}{\(i\)} & \(P\) & \(y_{m}\) }

\end{document}

여기에 이미지 설명을 입력하세요

보다 일반적인 구현: 열 수는 헤더에서 결정됩니다.

\documentclass{article}
\usepackage{array,booktabs}
\usepackage{xparse}

\newcommand{\myhrule}{\rule{1cm}{0.4pt}}

\ExplSyntaxOn

\NewDocumentCommand{\makeruledtabular}{mm}
 {% #1 = number of rows, #2 = header
  \hafid_ruledtabular:nn { #1 } { #2 }
 }

\seq_new:N \l__hafid_ruledtabular_header_seq
\tl_new:N \l__hafid_ruledtabular_first_tl

\cs_new_protected:Nn \hafid_ruledtabular:nn
 {
  % absorb the header as a sequence
  \seq_set_split:Nnn \l__hafid_ruledtabular_header_seq { & } { #2 }
  % split off the first item, which should be centered
  \seq_pop_left:NN \l__hafid_ruledtabular_header_seq \l__hafid_ruledtabular_first_tl
  % Define the auxiliary function based on the number of items in the header
  % At the end, if the header is 'A & B & C & D`, the function will be
  % defined to do '#1 & \myhrule & \myhrule & \myhrule \\', where #1 stands
  % for the current index in the loop
  \cs_set_protected:Nx \__hafid_ruledtabular_line:n
   {
    ##1
    \prg_replicate:nn { \seq_count:N \l__hafid_ruledtabular_header_seq }
     { & \exp_not:N \myhrule }
    \exp_not:N \\
   }
  \begin{tabular}
   {
    r
    *{ \seq_count:N \l__hafid_ruledtabular_header_seq } { w{c}{2cm} }
    @{}
   }
  \toprule
  \multicolumn{1}{c}{\tl_use:N \l__hafid_ruledtabular_first_tl} &
  \seq_use:Nn \l__hafid_ruledtabular_header_seq { & } \\
  \midrule
  \int_step_function:nN {#1} \__hafid_ruledtabular_line:n
  \bottomrule
  \end{tabular}
 }

\ExplSyntaxOff


\begin{document}

\makeruledtabular{10}{\(i\) & \(P\) & \(y_{m}\) }

\bigskip

\makeruledtabular{15}{A & B & C & D}

\end{document}

여기에 이미지 설명을 입력하세요

아이디어는 양식의 루프가 ..._function:...다른 것이 처리되기 전에 전체 루프를 전달한다는 것입니다. 따라서 3개의 행이 있는 3열 테이블의 경우

\__hafid_ruledtabular_line:n { 1 }
\__hafid_ruledtabular_line:n { 2 }
\__hafid_ruledtabular_line:n { 3 }

그리고 이 TeX가 첫 번째 항목을 처리하기 시작한 후에야

1 & \myhrule & \myhrule \\
2 & \myhrule & \myhrule \\
3 & \myhrule & \myhrule \\

전체 테이블 본문을 생성합니다.

답변4

루프를 사용하여 테이블을 만드는 방법은 다음과 같습니다.

\documentclass[11pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{geometry}
\geometry{top=1.8cm,bottom=3.3cm,left=0.5cm,right=0.5cm}
\usepackage{array}
\usepackage{longtable}
\usepackage{pgfplots}

\pgfplotsset{compat=1.18} 


\newcommand{\emptytablerows}[2]{
    \newtoks \rows{}
    \def \mycount{#2}
    \def \tableheading{#1}
    \def \emptyrow{}

    \foreach \i in {1,...,\mycount} {
        \global\rows\expandafter{\expanded{\the\rows \i \expandafter &  \emptyrow  \\} \hline}
    }

    \renewcommand{\arraystretch}{1.8}
    \begin{longtable}{|>{\centering\arraybackslash}m{0.5cm}|m{17cm}|}
        \multicolumn{2}{l}{\textbf{\tableheading}} \\ \endhead
        \hline%
        \the\rows
    \end{longtable}
    
    \renewcommand{\rows}{{}}
    \smallskip
}

\begin{document}
\emptytablerows{Temp}{6}
\end{document}

산출: 샘플 출력

관련 정보