Skip to content

Instantly share code, notes, and snippets.

@trpfrog
Last active November 18, 2019 18:22
Show Gist options
  • Save trpfrog/e1dcad6029f8d94795867e41229596ba to your computer and use it in GitHub Desktop.
Save trpfrog/e1dcad6029f8d94795867e41229596ba to your computer and use it in GitHub Desktop.
表計算ソフトからコピーした表データをLaTeX形式に変換し、クリップボードにコピーします。指数表記(E-01,E+00など)もLaTeXの数式に変換されます。
package net.trpfrog.latex_table_generator;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.util.Scanner;
public class LaTeXTableMaker {
public static final String INDENT = " ";
public static void main(String[] args) {
System.out.println("Welcome to LaTeX Table Generator!");
System.out.println("Please copy a table from Excel or Numbers and paste it here.");
System.out.println("After you pasted, please press the ENTER key TWO TIMES.");
Scanner sc = new Scanner(System.in);
StringBuilder table = new StringBuilder();
String temp = sc.nextLine();
table.append("\\begin{table}[H]");
table.append(System.lineSeparator());
indent(table,1);
table.append("\\begin{tabular}");
table.append("[");
for(int i=0; i<temp.split("\t").length;i++){
table.append("l|");
}
table.deleteCharAt(table.length()-1);
table.append("]");
table.append(System.lineSeparator());
indent(table,2);
table.append("\\hline \\\\");
table.append(System.lineSeparator());
indent(table,2);
buildLine(table,temp);
table.append("\\\\");
table.append(System.lineSeparator());
indent(table,2);
table.append("\\hline \\\\");
table.append(System.lineSeparator());
while(true){
temp = sc.nextLine();
if(temp.equals("")) break;
indent(table,2);
buildLine(table,temp);
table.deleteCharAt(table.length()-2);
table.append("\\\\");
table.append(System.lineSeparator());
}
indent(table,2);
table.append("\\hline");
table.append(System.lineSeparator());
indent(table,1);
table.append("\\end{tabular}");
table.append(System.lineSeparator());
table.append("\\end{table}");
System.out.println(table);
System.out.println();
setClipboard(table.toString());
System.out.println("The code has been copied to your clipboard!");
}
public static StringBuilder buildLine(StringBuilder table, String line){
for(String s : line.split("\t")){
table.append("$");
if(s.matches("^.*E[-\\+][0-9]+.*$")){
var tempExp = s.split("E[-\\+]");
table.append(tempExp[0]);
table.append(" \\times 10^{");
table.append(Integer.parseInt(tempExp[1]));
table.append("} ");
}else{
table.append(s);
}
table.append("$");
table.append(" & ");
}
return table;
}
public static void setClipboard(String text){
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection ss = new StringSelection(text);
cb.setContents(ss,ss);
}
public static StringBuilder indent(StringBuilder sb, int indents) {
for (int i = 0; i < indents; i++) {
sb.append(INDENT);
}
return sb;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment