[英]Convert UTF-8 to windows-1252 and write into csv in gwt 2.7.0 on tomcat v7
我在將UTF-8轉換為Windows-1252時遇到問題。 我必須輸出²,³,°之類的符號。 客戶希望在Excel中打開文件而不通過雙擊導入文件。
系統:gwt 2.7.0中的前端以及gxt 3.1.4的大量使用客戶端上的服務器是tomcat v7測試是在服務器上的gwt構建上完成的
現在的問題是,該應用程序支持日語符號,這些日語符號在UTF-8中可以完美顯示,而在Windows-1252中則不能。 另一方面,顯示²,³,°符號。 當前的解決方案是收集csv
的行,並將其放入FormPanel
內的隱藏字段中。 然后對FormPanel
進行編碼和提交。
public void postCsvForExcel( String url, Map<String, String> postData )
{
setSize( "0px", "0px" );
setVisible( false );
sinkEvents( Event.ONLOAD );
setMethod( FormPanel.METHOD_POST );
setEncoding( FormPanel.ENCODING_URLENCODED );
VerticalPanel panel = new VerticalPanel();
add( panel );
for( Entry<String, String> data : postData.entrySet() )
{
Hidden hiddenField = new Hidden( data.getKey(), data.getValue() );
panel.add( hiddenField );
}
SubmitButton submit = new SubmitButton();
panel.add( submit );
setAction( url );
FormElement.as( this.getElement() ).setAcceptCharset( "Cp1252" );
RootPanel.get().add( this );
submit();
}
日語字符僅顯示在標題中。 面對這個問題,我擴展了HttpServlet
的POST操作來轉換UTF-8
,如下所示,並刪除了FormElement.as( this.getElement() ).setAcceptCharset( "Cp1252" );
部分來自上述方法。
public class ExporterServlet extends HttpServlet {
public ExporterServlet() {
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
super.service(arg0, arg1);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filename = req.getParameter("filename");
String content = req.getParameter("content");
if(filename != null) {
//resp.setContentType( getContentType( filename ) + "; charset=utf-8" );
resp.setContentType( "text/csv" + "; charset=windows-1252" );
resp.setHeader( "Content-Disposition", "attachment;filename=\"" + filename + "\"" );
resp.setIntHeader("Expires", 0);
resp.setContentLength(content.length());
resp.setStatus(200);
//resp.setCharacterEncoding( "UTF-8" );
resp.setCharacterEncoding( "windows-1252" );
//byte[] destinationBytes = content.getBytes( "utf-8" );
ByteBuffer bb = ByteBuffer.wrap( content.getBytes() );
CharBuffer cb = Charset.forName( "UTF-8" ).decode( bb );
bb = Charset.forName( "windows-1252" ).encode( cb );
resp.getOutputStream().write( bb.array() );
resp.getOutputStream().flush();
}
}
}
但這似乎不起作用。 我在想什么嗎?
進一步的信息:我觀察到一件奇怪的事情。 盡管doPost
方法被調用對文件的編碼沒有影響。 我嘗試將其編碼為UTF-8,但輸出仍然是Windows-1252。 當我在以前的方法中刪除FormPanel
的編碼時,結果是UTF-8。
另一個問題是,Windows-1252的正確編碼是什么,我嘗試了cp1252和Windows-1252兩個版本,但無法發現結果的差異。
cp1252中不能顯示日語字符。 該指令本身未得到適當的檢查。 客戶不知道cp1252的功能。 在解決問題之前,應該已經檢查過了。
您可以添加以下代碼,然后重試:
filename = new String(filename.getBytes(), "ISO-8859-1");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.