我一直在尝试填写一个包含需要替换的占位符的单词模板(.docx)文件。
我能够重写模板,但文本没有换行符 我知道回车或新行(\ r \ n)在.docx文件中不起作用。我使用VariableReplace方法进行转换,但在使用变量replace时我无法放置br或factory.createBr()。
任何建议都会非常有用。下面是我试过的代码
import pymysql as MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","root","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("show tables")
# Fetch a single row using fetchone() method.
data = cursor.fetchall()
print (data)
# disconnect from server
db.close()
答案 0 :(得分:2)
来自Jason的链接已死。 这是当前链接:https://github.com/plutext/docx4j/blob/master/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/VariableReplace.java
以防将来被更改,只需使用以下函数并将其应用于包含换行符的字符串即可
/**
* Hack to convert a new line character into w:br.
* If you need this sort of thing, consider using
* OpenDoPE content control data binding instead.
*
* @param r
* @return
*/
private static String newlineToBreakHack(String r) {
StringTokenizer st = new StringTokenizer(r, "\n\r\f"); // tokenize on the newline character, the carriage-return character, and the form-feed character
StringBuilder sb = new StringBuilder();
boolean firsttoken = true;
while (st.hasMoreTokens()) {
String line = (String) st.nextToken();
if (firsttoken) {
firsttoken = false;
} else {
sb.append("</w:t><w:br/><w:t>");
}
sb.append(line);
}
return sb.toString();
}
答案 1 :(得分:0)