C#匯出excel表格(xls、xlsx)
阿新 • • 發佈:2019-02-06
預備知識:
關於excel
workbook:工作簿,每一個xls或xlsx相當於一個工作簿。
sheet:工作表,每個工作簿可以有多個工作表。工作表相當於一張紙,工作簿相當於一個本子,將過個工作表集合在一起。
row:行
column:列
cell:單元格(表格中的最小單位,接下來匯出表格就是對cell進行操作)
關於NPOI
POI:POI是一套用Java寫成的庫,能夠幫助開發者讀寫xls、xlsx等格式的檔案。
NPOI:POI的.net版本
XLS與XLSX:XLS是Office97-2003中表格檔案使用的格式,XLSX是Office2007以後預設的表格格式。C#使用NOPI匯出XLS和XLSX表格,語句是不同的。
編寫程式前需要在專案的引用中新增NOPI的引用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
!!!使用前需要先製作xls和xlsx各自的模板,並且需要寫入的單元格不要為空
接下來是xls檔案的匯出
//定義excel模板路徑
string xlsModelPath = System.Windows.Forms.Application.StartupPath + "\\excel\\模板.xls";
//複製要匯出的excel檔案
HSSFWorkbook xlsWorkBook;
//讀入剛複製的要匯出的excel檔案
using (FileStream file = new FileStream(xlsModelPath, FileMode.Open , FileAccess.Read))
{
xlsWorkBook = new HSSFWorkbook(file);
file.Close();
}
HSSFSheet sheet1 = (HSSFSheet)xlsWorkBook.GetSheetAt(0);
//對第二行第一列、第二行第二列寫入
HSSFCell cell1 = (HSSFCell)sheet1.GetRow(1).GetCell(0);
cell1.SetCellValue("部落格");
HSSFCell cell2 = (HSSFCell)sheet1.GetRow(1).GetCell(1);
cell2.SetCellValue("my_clearMind");
SaveFileDialog sfd = new SaveFileDialog();
string str = System.Environment.CurrentDirectory;
sfd.InitialDirectory = str + "\\report";
sfd.FileName = "excel匯出示例.xls";
sfd.Filter = "Excel 工作薄(*.xls)|*.xls";
//設定預設檔案型別顯示順序
sfd.FilterIndex = 1;
//儲存對話方塊是否記憶上次開啟的目錄
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
//建立檔案
FileStream files = new FileStream(sfd.FileName, FileMode.Create);
xlsWorkBook.Write(files);
files.Close();
MessageBox.Show("報表生成成功!");
}
xlsx程式碼類似xls,其中HSSF全部替換為XSSF
string xlsxModelPath = System.Windows.Forms.Application.StartupPath + "\\excel\\模板.xlsx";
XSSFWorkbook xlsxWorkBook;
using (FileStream file = new FileStream(xlsxModelPath, FileMode.Open, FileAccess.Read))
{
xlsxWorkBook = new XSSFWorkbook(file);
file.Close();
}
XSSFSheet xsheet1 = (XSSFSheet)xlsxWorkBook.GetSheetAt(0);
XSSFCell cell1 = (XSSFCell )sheet1.GetRow(1).GetCell(0);
cell1.SetCellValue("部落格");
XSSFCell cell2 = (XSSFCell)sheet1.GetRow(1).GetCell(1);
cell2.SetCellValue("my_clearMind");
SaveFileDialog sfd = new SaveFileDialog();
string str = System.Environment.CurrentDirectory;
sfd.InitialDirectory = str + "\\report";
sfd.FileName = "excel匯出示例.xlsx";
sfd.Filter = "Excel 工作薄(*.xlsx)|*.xlsx";
//設定預設檔案型別顯示順序
sfd.FilterIndex = 1;
//儲存對話方塊是否記憶上次開啟的目錄
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
//建立檔案
FileStream files = new FileStream(sfd.FileName, FileMode.Create);
xlsxWorkBook.Write(files);
files.Close();
MessageBox.Show("報表生成成功!");
}
原始碼下載
有用的話,記得留個評論!