1. 程式人生 > >C#路徑選擇及Excel讀寫操作

C#路徑選擇及Excel讀寫操作

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 System.IO; using System.Reflection; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using NPOI.XSSF.UserModel; namespace AutoData { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public string path = string.Empty; public string readstr1 = string.Empty; public string readstr2 = string.Empty; public string readstr3 = string.Empty; public string fileName = string.Empty; private string read_excel(int readsheet,int x,int y) { IWorkbook workbook = null; //新建IWorkbook物件 fileName = @path + "/123.xlsx"; FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 { workbook = new XSSFWorkbook(fileStream); //xlsx資料讀入workbook } else if (fileName.IndexOf(".xls") > 0) // 2003版本 { workbook = new HSSFWorkbook(fileStream); //xls資料讀入workbook } fileStream.Close(); //關閉檔案流 ISheet sheet = workbook.GetSheetAt(readsheet-1); //獲取第一個工作表 workbook.Close(); IRow row; row = sheet.GetRow(x-1); //int rowcount = sheet.LastRowNum; string cellValue = row.GetCell(y-1).ToString(); Console.WriteLine(cellValue); return cellValue; } private bool write_excle(int readsheet,int x,int y,string value) { //IWorkbook workbook = null; //新建IWorkbook物件 // fileName = @path + "/123.xlsx"; //FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //if (fileName.IndexOf(".xlsx") > 0) // 2007版本 //{ // workbook = new XSSFWorkbook(fileStream); //xlsx資料讀入workbook //} //else if (fileName.IndexOf(".xls") > 0) // 2003版本 //{ // workbook = new HSSFWorkbook(fileStream); //xls資料讀入workbook //} //ISheet sheet = workbook.GetSheetAt(readsheet - 1); //獲取第一個工作表 //ICell cell = sheet.GetRow(x - 1).GetCell(y - 1); //cell.SetCellValue(value); //workbook.Write(fileStream); //Console.WriteLine("寫入成功!"); //fileStream.Close(); //關閉檔案流 //workbook.Close(); IWorkbook workbook = new XSSFWorkbook(); workbook.CreateSheet("sheet1");//建立sheet fileName = @path + "/123.xlsx"; FileStream fs = File.Create(fileName);//path=mmm.xls; ISheet sheet = workbook.GetSheetAt(readsheet-1);//獲取sheet sheet.CreateRow(5).CreateCell(4).SetCellValue(value); workbook.Write(fs); return true; } private void button1_Click(object sender, EventArgs e) { System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog(); if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { path = fbd.SelectedPath; } textBox1.Text = path; } private void button2_Click(object sender, EventArgs e) { bool ret = false; readstr1 = read_excel(1,3,3); // textBox1.Text = readstr1; ret = write_excle(1, 4, 3, readstr1); if (ret) { textBox1.Text = "OK"; } } } }