<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>寫入 xls &#8211; 記下來</title>
	<atom:link href="https://noter.tw/tag/%E5%AF%AB%E5%85%A5-xls/feed/" rel="self" type="application/rss+xml" />
	<link>https://noter.tw</link>
	<description>一路上踩到的坑、遇到的問題，一點一滴記下來，希望能幫助到需要的人~</description>
	<lastBuildDate>Sat, 07 Nov 2020 14:49:07 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.3</generator>

<image>
	<url>https://noter.tw/wp-content/uploads/cropped-old-1130742_1920-1-32x32.jpg</url>
	<title>寫入 xls &#8211; 記下來</title>
	<link>https://noter.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Java 寫入 Excel 文件(xls, xlsx) – 使用 Apache POI</title>
		<link>https://noter.tw/6723/java-%e5%af%ab%e5%85%a5-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/</link>
					<comments>https://noter.tw/6723/java-%e5%af%ab%e5%85%a5-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/#respond</comments>
		
		<dc:creator><![CDATA[黃小蛙]]></dc:creator>
		<pubDate>Fri, 29 Nov 2019 05:34:06 +0000</pubDate>
				<category><![CDATA[一般程式]]></category>
		<category><![CDATA[xlsx]]></category>
		<category><![CDATA[Apache POI]]></category>
		<category><![CDATA[讀取 xlsx]]></category>
		<category><![CDATA[寫入 excel]]></category>
		<category><![CDATA[寫入 xls]]></category>
		<category><![CDATA[2020]]></category>
		<category><![CDATA[excel]]></category>
		<category><![CDATA[jxl]]></category>
		<category><![CDATA[xls]]></category>
		<category><![CDATA[2019]]></category>
		<guid isPermaLink="false">https://noter.tw/?p=6723</guid>

					<description><![CDATA[<p>之前寫過一篇 Java 讀取 Excel 文件(xls, xlsx) – 使用 Apache POI，記錄用 POI 讀取 Excel 的教學，這篇要補足「寫入」的教學。 小蛙會切割成幾個步驟來講（還&#46;&#46;&#46;</p>
<p>這篇文章 <a rel="nofollow" href="https://noter.tw/6723/java-%e5%af%ab%e5%85%a5-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/" data-wpel-link="internal">Java 寫入 Excel 文件(xls, xlsx) – 使用 Apache POI</a> 最早出現於 <a rel="nofollow" href="https://noter.tw" data-wpel-link="internal">記下來</a>。</p>
]]></description>
										<content:encoded><![CDATA[
<p>之前寫過一篇 <a href="https://noter.tw/4300/java-%e8%ae%80%e5%8f%96-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/" data-wpel-link="internal">Java 讀取 Excel 文件(xls, xlsx) – 使用 Apache POI</a>，記錄用 POI 讀取 Excel 的教學，這篇要補足「寫入」的教學。</p>



<span id="more-6723"></span>



<p>小蛙會切割成幾個步驟來講（還沒有下載跟導入 POI 的話，請先看<a href="https://noter.tw/4300/java-%e8%ae%80%e5%8f%96-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/" data-wpel-link="internal">前一篇</a>）</p>



<ul class="my-li bg-darkblue wp-block-list"><li>開啟 Excel：<a href="#exist">讀入既有的</a>、<a href="#new">建立新的</a></li><li><a href="#data">設定儲存格資料</a></li><li><a href="#writeout">寫出 Excel</a></li></ul>



<p>小蛙最近要用到，之前都是這樣子寫，但是後來發現當要寫的資料大到一定程度的時候，這樣的寫法會出問題，所以最後面會加映<a href="#mass">寫出大量資料</a>時候的作法，不過其實也可以直接用最後面的那種做法就好了！</p>



<h2 class="para wp-block-heading" id="exist">開啟 Excel &#8211; 讀入既有的</h2>



<p>程式碼如下，直接看應該不難看懂，多寫 .xls 跟 .xlsx 的判斷，如果自己使用的狀況有固定，就不需要多做這一步驟，直接去建立 xls 對應的 <code>HSSFWorkbook</code> 或 xlsx 對應的 <code>XSSFWorkbook</code>。</p>



<pre class="wp-block-preformatted wp-block-syntaxhighlighter-code">// 讀取既有的
String path = "要匯出的檔案 e.g. C:\\測試.xlsx";
Workbook wb = null;
String extString = path.substring(path.lastIndexOf("."));
InputStream is = new FileInputStream(path);
if(".xls".equals(extString)){
   wb = new HSSFWorkbook(is);
}else if(".xlsx".equals(extString)){
   wb = new XSSFWorkbook(is);
}</pre>



<h2 class="para wp-block-heading" id="new">開啟 Excel &#8211; 建立新的</h2>



<p>如果本來沒有這個檔案就要用這段，先直接 new 出對應的 Workbook，在後面的步驟再把 Excel 寫出。</p>



<pre class="wp-block-preformatted wp-block-syntaxhighlighter-code">// 開新檔案
String path = "要匯出的檔案 e.g. C:\\測試.xlsx";
Workbook wb = null;
String extString = path.substring(path.lastIndexOf("."));
if(".xls".equals(extString)){
    wb = new HSSFWorkbook();
}else if(".xlsx".equals(extString)){
    wb = new XSSFWorkbook();
}else{
    System.out.println("無效檔案");
    return;
}</pre>



<h2 class="para wp-block-heading" id="data">設定儲存格資料</h2>



<p>POI 對 Excel 的處理脈絡是這樣，先有一個 Workbook，把他看成是一個 Excel，下一層是頁籤 Sheet，再下一層是橫的 Row，最後就是儲存格 Cell，前面的步驟我們建立(取得)了 Workbook，下一步就是要建立 Sheet &gt; Row &gt; Cell，只要記住這個順序很快就可以把自己要寫的資料設定好了，下面的程式碼是把九九乘法表輸出到 Excel 裡。</p>



<pre class="wp-block-preformatted wp-block-syntaxhighlighter-code">// 設定儲存格資料
Sheet sheet = wb.createSheet(); 
Row row = null;
Cell cell = null;
for(int r = 0; r &lt; 9; r++){
    row = sheet.createRow(r);
    for(int c = 0; c &lt; 9; c++){
        cell = row.createCell(c);
	cell.setCellValue(
            (c + 1) + " x " + (r + 1) + " = " + ((r + 1) * (c + 1))
        );
    }
}</pre>



<h2 class="writeout wp-block-heading">寫出 Excel</h2>



<p>內容都設置好之後，最後一個步驟就是把這些變動寫到 Excel 檔案上啦！</p>



<pre class="wp-block-preformatted wp-block-syntaxhighlighter-code">// 寫出 Excel
try {
    FileOutputStream fos = new FileOutputStream(new File(path));
    wb.write(fos);
    fos.flush();
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}</pre>



<p>到這邊就結束了！很簡單吧！上面全部組合起來應該就可以動了。</p>



<h2 class="para wp-block-heading" id="mass">處理大量資料</h2>



<p>如果資料量非常大的話，以小蛙的狀況來說要寫的資料量超過 3000 筆的時候，就會一直噴 <code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space</code> 的錯誤，Google 查了一些資料發現除了上面提到的 <code>HSSFWorkbook</code> 跟 <code>XSSFWorkbook</code> 之外，還有一個叫做 <code>SXSSFWorkbook</code> 的類別。</p>



<p><code>SXSSFWorkbook</code> 的運作方式跟 <code>HSSFWorkbook</code> 及 <code>XSSFWorkbook</code> 不同，<code>SXSSFWorkbook</code> 會先以「暫存檔」的方式寫回硬碟，最後輸出的時候再把他們存回 Excel 裡面，這樣一來就不會出現 Out Of Memory 的問題啦！不過如果內容處理沒弄好也還是會 OOM 就是～附上相關程式碼。</p>



<pre class="wp-block-preformatted wp-block-syntaxhighlighter-code">// 大量資料用 SXSSFWorkbook
String path      = "要匯出的檔案 e.g. C:\\測試.xlsx";
// 設定幾筆之後，就先寫到硬碟的暫存檔
SXSSFWorkbook wb = new SXSSFWorkbook(100);
Sheet sheet      = wb.createSheet();
FileOutputStream fileOut = new FileOutputStream(path);	
Row row   = null;
Cell cell = null;
for(int r = 0; r &lt; 9; r++){
    row = sheet.createRow(r);
    for(int c = 0; c &lt; 9; c++){
        cell = row.createCell(c);
        cell.setCellValue(
            (c + 1) + " x " + (r + 1) + " = " + ((r + 1) * (c + 1)));
    }
}
wb.write(fileOut);
fileOut.flush();
fileOut.close();
wb.dispose();</pre>



<p><strong>Excel 相關文章：</strong></p>



<ul class="my-li bg-darkblue wp-block-list"><li><a href="https://noter.tw/9117/excel-filter-and-validation/" data-wpel-link="internal">加入篩選器及下拉選單 (資料驗證)</a></li><li><a href="https://noter.tw/9063/excel-auto-search-and-fill-data-by-vlookup-index-match/" data-wpel-link="internal">搜尋表格 填入資料 強大的 VLOOKUP, INDEX, MATCH</a></li><li><a href="https://noter.tw/9061/split-a-excel-to-files/" data-wpel-link="internal">分拆 Excel 成多個檔案 ( Split A Excel to Files)</a></li><li><a href="https://noter.tw/6550/excel-%e4%bd%bf%e7%94%a8-poi-%e8%ae%80%e5%8f%96%e6%96%87%e5%ad%97%e6%a0%bc%e5%bc%8f%e6%97%a5%e6%9c%9f%e5%8d%bb%e8%ae%8a%e6%88%90%e6%95%b8%e5%ad%97%e7%9a%84%e5%95%8f%e9%a1%8c/" data-wpel-link="internal">Excel 使用 POI 讀取文字格式日期卻變成數字的問題</a></li><li><a href="https://noter.tw/4300/java-%e8%ae%80%e5%8f%96-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/" data-wpel-link="internal">Java 讀取 Excel 文件(xls, xlsx) – 使用 Apache POI</a></li><li><a href="https://noter.tw/2711/oracle-%e5%8c%af%e5%85%a5%e5%8c%af%e5%87%ba-excel-%e9%80%8f%e9%81%8e-sql-developer/" data-wpel-link="internal">Oracle 匯入/匯出 Excel (透過 SQL Developer)</a></li><li><a href="https://noter.tw/1732/jsp%e5%b0%87%e8%b3%87%e6%96%99%e5%8c%af%e5%87%ba%e6%88%90excel%e7%9b%b4%e6%8e%a5%e4%b8%8b%e8%bc%89-by-jexcelapi-jxl/" data-wpel-link="internal">JSP將資料匯出成Excel直接下載 by JExcelApi (jxl)</a></li><li><a href="https://noter.tw/1569/java-excel-jxl/" data-wpel-link="internal">Java + Excel = JXL</a></li><li><a href="https://noter.tw/119/ncr-%e8%99%95%e7%90%86%e6%96%b9%e5%bc%8f%ef%bc%9ajava-vba/" data-wpel-link="internal">NCR &amp;#xxxxx; 處理方式：Java &amp; VBA</a></li></ul>
<p>這篇文章 <a rel="nofollow" href="https://noter.tw/6723/java-%e5%af%ab%e5%85%a5-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/" data-wpel-link="internal">Java 寫入 Excel 文件(xls, xlsx) – 使用 Apache POI</a> 最早出現於 <a rel="nofollow" href="https://noter.tw" data-wpel-link="internal">記下來</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://noter.tw/6723/java-%e5%af%ab%e5%85%a5-excel-%e6%96%87%e4%bb%b6xls-xlsx-%e4%bd%bf%e7%94%a8-apache-poi/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
