[C#] 取出Resources中的Excel/Word檔來使用

  • 6266
  • 0
  • C#
  • 2009-12-24

取出Resources中的Excel/Word檔來使用

操作環境: ,


這裡以Excel為例
如果我們需要一個Excel檔做範本
可以先把它拉到Resources中

image

然後在需要的時候才把它從Resources取出來使用
不過因為它沒辦法像圖檔可以直接操作
所以需要點小技巧
看程式碼

private void button1_Click(object sender, EventArgs e)
{
    byte[] sampleXls = Properties.Resources.sample; //取出Resources中的sample.xls檔
    FileStream outputExcelFile = new FileStream("C:\\sample.xls", FileMode.Create, FileAccess.Write); //存到C槽
    outputExcelFile.Write(sampleXls, 0, sampleXls.Length);
    outputExcelFile.Close();
}

 

把它存成一般的Excel檔案後
就可以對它做一般Excel的讀寫操作了

如果不喜歡固定存到某個位置讓別人知道
可以搭配Path類別幫你產生不重複的暫存檔

private void button2_Click(object sender, EventArgs e)
{
    string tmpFile = Path.GetTempFileName(); //取一個不重複的暫存檔名 (副檔名.tmp)
 
    byte[] sampleXls = Properties.Resources.sample;
    FileStream outputExcelFile = new FileStream(tmpFile, FileMode.Create, FileAccess.Write); //存到temp檔
    outputExcelFile.Write(sampleXls, 0, sampleXls.Length);
    outputExcelFile.Close();
 
    string xlsFile = Path.ChangeExtension(tmpFile, "xls"); //變更副檔名為.xls
    File.Move(tmpFile, xlsFile);
 
    MessageBox.Show("存到[" + xlsFile + "]成功");
}

 

[Code下載]

 

 

by sam319