2016-08-19 16 views
1

NPOIを使用してExcelファイル(.xls)のセル値を編集する以下のプログラムを作成しましたが、プログラムはエラーも例外もなく実行されますが、NPOIを使用してExcelのセル値を編集するプログラム。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 
using System.Web; 
using NPOI.XSSF.UserModel; 
using NPOI.XSSF.Model; 
using NPOI.HSSF.UserModel; 
using NPOI.HSSF.Model; 
using NPOI.SS.UserModel; 
using NPOI.SS.Util; 
namespace Project37 
{ 
    class Class1 
    { 
     public static void Main() 
     { 
      string pathSource = @"C:\Users\mvmurthy\Desktop\abcd.xls"; 
      FileStream fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite); 
      HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true); 
      HSSFSheet sheet = (HSSFSheet)templateWorkbook.GetSheet("Contents"); 
      HSSFRow dataRow = (HSSFRow)sheet.GetRow(4); 
      dataRow.Cells[2].SetCellValue("foo"); 
      MemoryStream ms = new MemoryStream(); 
      templateWorkbook.Write(ms); 
      ms.Close(); 
     }  
    } 
} 

答えて

3

を更新取得されていないあなたは、そうでない場合は、あなたが実際にあなたがディスクに加えた変更を保存していない、あなたの変更されたファイルを保存するためにFileStreamの代わりMemoryStreamを使用する必要があります。

FileStreamのような使い捨てオブジェクトを囲む方が、usingステートメントに囲む方が、このオブジェクトが有効範囲外になったときに自動的に廃棄されることに注意してください。

だからあなたのコードは次のようになります。

string pathSource = @"C:\Users\mvmurthy\Desktop\abcd.xls"; 
HSSFWorkbook templateWorkbook; 
HSSFSheet sheet; 
HSSFRow dataRow; 

using (var fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite)) 
{ 
    templateWorkbook = new HSSFWorkbook(fs, true); 
    sheet = (HSSFSheet)templateWorkbook.GetSheet("Contents"); 
    dataRow = (HSSFRow)sheet.GetRow(4); 
    dataRow.Cells[0].SetCellValue("foo"); 
} 

using (var fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite)) 
{ 
    templateWorkbook.Write(fs); 
} 
+0

ありがとうございました!アンディ・コルネイエフ – manvitha

関連する問題