2014年7月15日 星期二

[. Net C#]匯出Excel

以下為C# .Net匯出Excel範例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Windows.Forms;

private void ExportExcel
{
    System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
    excelApp.Visible = false;
    excelAppUserControl = true;
    Microsoft.Office.Interop.Excel.Workbooks workbooks = excelApp.Workbooks; 
    Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add("/test.xlsx"); //此處套用來源Excel
    Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
    Microsoft.Office.Interop.Excel._Worksheet worksheet = (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //選擇第一個Sheet
  if (worksheet == null)
     {
       //找不到Sheet處理動作
     }
  else
     {
         //新增一欄
         Range range = worksheet.get_Range("A1", "L1");
         range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
         worksheet.get_Range("A1", "L1").Insert(Type.Missing, Type.Missing);
  //新增一列
  Range range = worksheet.get_Range("D1", "D4");
         range.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
         Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
         //合併儲存格
         worksheet.get_Range("B1", "C1").Merge(worksheet.get_Range("B1", "C1").MergeCells);
         //設定Row行 填入資料
  int row_ = 4;
         worksheet.Cells[row_, 1] = "Hello World";
  //儲存檔案
  string savaPath = "~/Temp/" + "Test.xlsx";
         workbook.SaveAs(savaPath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
         workbook.Close();
      }
}



沒有留言:

張貼留言