顯示具有 Microsoft Office 標籤的文章。 顯示所有文章
顯示具有 Microsoft Office 標籤的文章。 顯示所有文章

2019/03/29

Java POI 讀取整個Sheet以及寫入值至cell和取得公式計算後結果


用到的jar有以下幾個
poi-3.17.jar
poi-ooxml-3.17.jar
poi-ooxml-schemas-3.17.jar
commons-collections4-4.1.jar
xmlbeans-2.6.0.jar

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

/**
 * @see <a href="https://poi.apache.org/components/spreadsheet/index.html">POI-HSSF and POI-XSSF/SXSSF - Java API To Access Microsoft Excel Format Files</a>
 */
public class Excel {
    private boolean isExcel2003 = false;
    private Workbook workbook;
    private Sheet sheet;


    public Excel() throws IOException {
        this(Excel.class.getResource("test.xlsx").getPath());
    }

    public Excel(String path) throws IOException {
        this.isExcel2003 = (path.matches("^.+\\.(?i)(xls)$")) ? true : false;

        FileInputStream fileInputStream = new FileInputStream(path);
        if (this.isExcel2003) {
            this.workbook = new HSSFWorkbook(fileInputStream);
        } else {
            //2007
            this.workbook = new XSSFWorkbook(fileInputStream);
        }
        this.selectSheet(0);
    }

    public Sheet selectSheet(int index) {
        if (index < 0 || index > (this.getSheetsCount() - 1)) return null;
        this.sheet = this.workbook.getSheetAt(index);
        return this.sheet;
    }

    public int getSheetsCount() {
        return this.workbook.getNumberOfSheets();
    }

    public void readAllCell(int index) {
        this.selectSheet(index);

        Iterator<Row> rowIterator = this.sheet.rowIterator();
        while (rowIterator.hasNext()) {

            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();
                switch (cell.getCellTypeEnum()) {
                    case FORMULA:
                        System.out.println(cell.getCellFormula());
                        break;
                    case STRING:
                        System.out.println(cell.getStringCellValue());
                        break;
                    case NUMERIC:
                        System.out.println(cell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        System.out.println(cell.getBooleanCellValue());
                        break;
                    default:
                        break;
                }
            }
        }
    }

    public Object getCalculateRule(CellReference reference) {
        FormulaEvaluator evaluator = this.workbook.getCreationHelper().createFormulaEvaluator();
        Row row = this.sheet.getRow(reference.getRow());
        Cell cell = row.getCell(reference.getCol());
        CellValue value = evaluator.evaluate(cell);

        switch (value.getCellTypeEnum()) {
            case STRING:
                return value.getStringValue();
            case NUMERIC:
                return value.getNumberValue();
            case BOOLEAN:
                return value.getBooleanValue();
            default:
                return null;
        }
    }

    public void setValue(CellReference reference, Object v) {
        Row row = this.sheet.getRow(reference.getRow());
        if (row == null)
            row = sheet.createRow(reference.getRow());
        Cell cell = row.getCell(reference.getCol());
        if (v instanceof String)
            cell.setCellValue((String) v);
        else if (v instanceof Double)
            cell.setCellValue((Double) v);
        else if (v instanceof Boolean)
            cell.setCellValue((Boolean) v);
        else if (v instanceof Date)
            cell.setCellValue((Date) v);
        else if (v instanceof Calendar)
            cell.setCellValue((Calendar) v);
        else if (v instanceof RichTextString)
            cell.setCellValue((RichTextString) v);
    }

}

2016/07/25

Excel 結合多個儲存格(日期)

客戶有天問我Excel該怎麼讓每一行的儲存格值合併起來為一格

以上圖為例公式則是


#& = + 
=A2 & "_" & B2& "_" &  C2 & "_" & D2 & "_" & E2



如果遇到日期等特殊數值套用上面公式則會變成數值或其他格式



這時候透過Text公式即可解決

#Text(value, format)
=TEXT(A2,"YYYY/MM/DD") & "_"&B2&"_"&C2&"_"&D2&"_"&E2&"_"&F2



2016/07/23

C#.Net 釋放Excel COM程序及記憶體

使用Excel COM元件時開啟或寫入資料完後有調用其方法關閉
但仍無法釋放該元件所使用的記憶體及程序,關閉主程式時會另Excel COM元件成為殭屍並鎖住其表單



正確釋放應該是先使用「Marshal.ReleaseComObject」釋放COM元件,接著在透過GC.CollectGC.WaitForPendingFinalizers釋放記憶體及程序

程式碼如下:


        /// <summary>
        /// Close Excel
        /// </summary>
        private void CloseExcel()
        {
            if (sheet != null)
            {
                Marshal.ReleaseComObject(this.sheet);
                this.sheet = null;
            }

            if (workbook != null)
            {
                //Close workbook
                this.workbook.Close(0);
                Marshal.ReleaseComObject(this.workbook);
                this.workbook = null;
            }

            if (app != null)
            {
                //Close app
                this.app.Quit();
                Marshal.ReleaseComObject(this.app);
                this.app = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            MessageBox.Show("Done","Gererate", MessageBoxButtons.OK);
            Process.Start("explorer.exe", CurrentPath);
        }

2016/07/08

C#.Net Filtering DataGridView

程式碼:
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;

namespace TestProject
{
    public partial class Form1 : Form
    {
        private String text
        {
            get { return this.textBox1.Text; }
        }

        private readonly String sqlStr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}\Database1.accdb;Persist Security Info=False;" , Directory.GetCurrentDirectory());
        private OleDbConnection conn;
        private OleDbCommand cmd;

        public Form1()
        {
            InitializeComponent();
            DBinit();
        }

        private void DBinit()
        {
            conn = new OleDbConnection(sqlStr);
            conn.Open();
            string sql = "Select * from cyfang";
            cmd = new OleDbCommand(sql, conn);
            cmd.CommandType = CommandType.Text;
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            dataGridView1.DataSource = table;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(text) != true)
            {
                BindingSource bs = new BindingSource();
                bs.DataSource = dataGridView1.DataSource;
                //filter
                bs.Filter = String.Format("username like '%{0}%'", text);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            conn.Close();
        }
    }
}

執行結果:


C#.Net Connect Access 2007

程式碼:
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;

namespace TestProject
{
    public partial class Form1 : Form
    {
        private String text
        {
            get { return this.textBox1.Text; }
        }

        private readonly String sqlStr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}\Database1.accdb;Persist Security Info=False;" , Directory.GetCurrentDirectory());
        private OleDbConnection conn;
        private OleDbCommand cmd;

        public Form1()
        {
            InitializeComponent();
            DBinit();
        }

        private void DBinit() {
            conn = new OleDbConnection(sqlStr);
            conn.Open();
            string sql = "Select * from cyfang";
            cmd = new OleDbCommand(sql, conn);
            cmd.CommandType = CommandType.Text;
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            dataGridView1.DataSource = table;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            conn.Close();
        }
    }
}

執行結果:

C#.Net 解決 Access 2007 microsoft.ace.oledb.12.0' 提供者並未登錄於本機電腦上

下載2007 Office system 驅動程式:資料連線元件,用管理者權限開啟命令提示字元輸入
AccessDatabaseEngine.exe /passive
重啟VS執行即可

2016/07/03

C#.Net create Excel file


程式碼:
private void CreateExcelFile()
{
 EXCEL.Application app = new EXCEL.Application();

 //隱藏Excel程式
 app.visible = false;

 //建立工作簿
 EXCEL.Workbook workbook = app.Workbooks.Add(EXCEL.XlWBATemplate.xlWBATWorksheet);

 //取得工作表
 EXCEL.Worksheet sheet = (EXCEL.Worksheet)workbook.Worksheets[1];

 //給予工作表名稱
 sheet.Name = "sheet1";

 //給予該欄位值
 sheet.Cells[1, 1] = "Name";
 sheet.Cells[1, 2] = "Age";
 sheet.Cells[2, 1] = "Wang";
 sheet.Cells[2, 2] = "18";

 //儲存Excel
 sheet.SaveAs(path);
 //關閉工作簿
 workbook.Close();
 //關閉Excel程式
 app.Quit();
}

2016/06/15

C#.Net 讀取行列資料

程式碼:
class Ex{
    private EXCEL.Application _app;
    private EXCEL.Worksheet _sheet;
    private EXCEL.Workbook _workbook;
    private int _rowCount = 5;
    private int _columnCount = 5;
     
    public Ex(String fileName){
        //調用EXCEL
        this._app = new EXCEL.Application();
 
        //隱藏EXCEL
        this._app.Visible = false;
 
        //開啟檔案
        this._workbook = this._app.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing);
        this._sheet = (EXCEL.Worksheet)_workbook.Worksheets[1];
    }
     
    public void Show(){
        var cells = this._sheet.Cells;

        for (int r = 1; r <= _rowCount; r++) {
            for (int c = 1; c <= _columnCount; c++){
                //初始行列為1
                var content = (Object)(cells[r, c] as EXCEL.Range).Value;
                if (content != null)
                    if (String.IsNullOrEmpty(content.ToString()) != true)
                        Console.WriteLine(content);
                }
            }
    }
}

C#.Net 取得Excel行列


程式碼:
class Ex{
    private EXCEL.Application _app;
    private EXCEL.Worksheet _sheet;
    private EXCEL.Workbook _workbook;
    
    public Ex(String fileName){
        //調用EXCEL
        this._app = new EXCEL.Application();

        //隱藏EXCEL
        this._app.Visible = false;

        //開啟檔案
        this._workbook = this._app.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing);
        this._sheet = (EXCEL.Worksheet)_workbook.Worksheets[1];
    }
    
    public void Show(){
        //列
        Console.WriteLine(this._sheet.UsedRange.Cells.Columns.Count);
        //行
        Console.WriteLine(this._sheet.UsedRange.Cells.Rows.Count);
    }
}

2015/08/17

C#.Net Access 2007 ISAM

原本的連接字串為這樣但是會出現ISAM錯誤
原因有可能是因為連接字串就打錯
以下面這行程式碼來說是錯在DataBase Password

Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;DataBase Password='{1}';Data Source={0};


只要在DataBase Password前面要加上Jet才可以
Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Jet OLEDB:DataBase Password='{1}';Data Source={0};

2015/03/28

C#.Net DataTable to Excel File


using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace Sample
{
    public partial class Form1 : Form
    {
        private readonly String[] Headers = { "姓名", "座號", "國文成績" };
        private readonly String[] Users = { "王小明", "陳大吉", "洪船長" };
        private readonly int[] CH_Score = { 57, 80, 92 };
        private readonly int MAX = 3;
        private DataTable table = new DataTable();


        public Form1()
        {
            InitializeComponent();
            table.Columns.Add("Header");
            table.Columns.Add("User");
            table.Columns.Add("Score");
        }


        private void button1_Click(object sender, EventArgs e)
        {
            for (int index = 0; index < MAX; index++)
            {
                DataRow row = table.NewRow();
                row["Header"] = Headers[index];
                row["User"] = Users[index];
                row["Score"] = CH_Score[index];
                table.Rows.Add(row);
            }

            DataTableToCSV(table);
        }

        private void DataTableToCSV(DataTable table)
        {
            Excel.Application excel = new Excel.Application();

            try
            {
                if (excel == null)
                    throw new Exception();
                //不顯示Excel
                excel.Visible = false;

                //不顯示Excel錯誤
                excel.DisplayAlerts = false;

                Excel._Workbook workbook = excel.Workbooks.Add();

                //Excel已1為開頭
                Excel._Worksheet sheet = (Excel._Worksheet)workbook.Worksheets[1];


                int point = 0;

                foreach (var row in table.AsEnumerable())
                {
                    int maxLength = row.ItemArray.Length;
                    for (int index = 0; index < maxLength; index++)
                        sheet.Cells[point + 1, index + 1] = row.ItemArray[index];

                    point++;
                }

                workbook.SaveAs(String.Format("{0}\\{1}.xls", Directory.GetCurrentDirectory(), DateTime.Now.Ticks),
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                      Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing,
                      Type.Missing, Type.Missing, Type.Missing);


                workbook.Close(false, Type.Missing, Type.Missing);
                workbook = null;
                sheet = null;
                excel = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("無法將資料寫入Excel");
            }
        }

    }
}



執行結果:


2014/06/16

Excel2007 下拉式選單

選擇資料/資料工具/資料驗證/資料驗證



 儲存格內允許清單

並輸入來源資料,資料來源可以使用該資料表或鍵入資料


2013/12/22

C#.Net 使用Excel函數

加入Microsoft.Office.Interop.Excel元件




程式碼:
using System;
using EXCEL = Microsoft.Office.Interop.Excel;
namespace CallExcelFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            EXCEL.Application excel = new EXCEL.Application();
            Console.WriteLine(excel.WorksheetFunction.Log(1024,2));
            Console.Read();
        }
    }
}

執行結果:

參考資料:
http://alvincho.blogspot.tw/2009/04/c-excel-black-scholes.html
http://msdn.microsoft.com/zh-tw/library/ms173186(v=vs.80).aspx

2013/11/12

Java Use Apache POI read word file


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.POITextExtractor;
import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.hwpf.extractor.Word6Extractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;

public class ReadWord {
 public static void main(String[] args) throws IOException,
   InvalidFormatException, OpenXML4JException, XmlException {
  FileInputStream fileInputStream = new FileInputStream(new File(
    "C:\\Users\\CY\\Desktop\\a.docx"));
  POITextExtractor extractor = ExtractorFactory
    .createExtractor(fileInputStream);
  if (extractor instanceof Word6Extractor) {
   // Word 95
   Word6Extractor extractor2 = (Word6Extractor) extractor;
   System.out.println(extractor2.getText());
  } else if (extractor instanceof WordExtractor) {
   // Word 2003
   WordExtractor extractor2 = (WordExtractor) extractor;
   System.out.println(extractor2.getText());
  } else if (extractor instanceof XWPFWordExtractor) {
   // Word 2007
   XWPFWordExtractor extractor2 = (XWPFWordExtractor) extractor;
   System.out.println(extractor2.getText());
  }

 }
}







參考資料:
http://poi.apache.org/
http://poi.apache.org/hwpf/
http://blog.changyy.org/2012/04/java-apache-poi-wordexcelpowerpoint.html
http://poi.apache.org/text-extraction.html

2013/10/25

C# 使用DataGridView載入Excel 2003 或 Excel 2007 資料

DataGridView是一個以表格為顯示的元件,這個元件在C#中算是非常好用。不只可讀取Office資料,也可讀取SQL或MySQL的資料,非常具有彈性以及使用價值

這次要將讀取到的Office資料透過DataGridView去顯示,以前有寫過類似的東西,知道必須透過OLE DB去取得資料

什麼是OLE(Object Linking and Embedding)?OLE就是可以在檔案內嵌入不同的檔案
舉例:Word內可嵌入Excel、圖片、PDF等等的檔案

OLE DB是為了擴充不支援SQL語法的程式,而透過COM元件去實做出來的

程式內容會因為openToolStripMenuItem點擊事件『openToolStripMenuItem_Click』而觸發

private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Excel 2003|*.xls|Excel 2007|*.xlsx";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //File Path
                string path = dialog.FileName;
                string oleStr = GetOleStr(ref path);

                try
                {
                    using (OleDbConnection ole = new OleDbConnection(oleStr))
                    {
                        //OLE SQL
                        const string sql = @"SELECT * FROM [tableName$]";

                        using (OleDbCommand cmd = new OleDbCommand(sql, ole))
                        {
                            using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                            {
                                DataTable table = new DataTable();
                                adapter.Fill(table);
                                dataGridView1.DataSource = table;
                            }
                        }

                    }
                }
                catch (OleDbException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

2013/09/29

C#.Net PowerPoint簡報輸出成圖片

同學最近在趕10/4評鑑,需要將PPT輸出成圖片XDDD
他丟了篇文章『[C#]Export PowerPoint file to photos』給我,學習學習XD

首先,先將MS PowerPoint 12.0 Object Library加入參考



將以下程式碼貼到程式內

2013/05/13

C#.Net 讀取PowerPoint文字方塊內容

今天有跟同學稍微討論一下KINECT開發,他有提出一個問題是想取得PowerPoint的文字
既然我有興趣,就下海來寫啦XD

我沒記錯的話,必須先安裝好Office不然到時候呼叫COM元件會有問題
安裝好Office之後,Visual Studio2010會在加入參考的.Net出現Office家族的套件

今天範例是使用WPF實做

2013/03/28

C# DataGridView讀入Excel

公司總是會有很多的Excel檔案,當要把這些檔案集合起來並且彙整成一個資料庫的時候
麻煩的不在於資料庫的規劃,而是在於那些Excel檔案的格式問題…

而且要將那些資料一筆一筆的key in進去資料庫又很辛苦,所以就產生這篇文章了XDDD

在進行講解前可以先去看一下這篇文章『[C#]-讀取excel檔案寫入MS SQL Server』,這篇文章我個人認為寫得比微軟MVP還要清楚;而且又附有版本對應的命令

2013/03/21

Word 2007 在特定頁數插入頁碼

通常文件第一頁都是封面,接著就目錄等等的…
那些都不會加上頁碼,只會在文章的開始才會加上頁碼

那會寫這篇文章,也不是為了用論文或是寫技術文件…
而是上次在中山工商兼助教的時候,電通系老師問的問題,順便隨手寫下這篇文章了


2012/08/10

使用Word2007做出PowerPoint2007簡報檔

學長的論文常常都是doc或docx檔案,不過有時候要上台報告時必須使用ppt的檔案
也不可能用密密麻麻的文字去報告吧,可能會被自己的老闆打趴在地板
最不希望的是每天都要在那邊剪剪貼貼

所以在書上看到這方法,也順便分享給其他人吧!