2010-01-06 41 views
10

Tôi có tệp Excel có 5 trang tính và tôi muốn có mã C# để mở nó và khi nó được mở, tôi muốn kích hoạt trang tính số 3.Mở tệp Excel trên một trang tính cụ thể

Tôi có thể làm như thế nào?

+0

Bạn có muốn tự động hóa excel hoặc bạn muốn hiển thị dữ liệu trong lưới trong ứng dụng của mình? Hay cái gì khác? –

Trả lời

23

Như thế này:

using Excel; 

Excel.Application excelApp = new Excel.ApplicationClass(); 

    // if you want to make excel visible to user, set this property to true, false by default 
    excelApp.Visible = true; 

// open an existing workbook 
string workbookPath = "c:/SomeWorkBook.xls"; 
    Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 
     0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", 
     true, false, 0, true, false, false); 



// get all sheets in workbook 
    Excel.Sheets excelSheets = excelWorkbook.Worksheets; 

    // get some sheet 
string currentSheet = "Sheet1"; 
    Excel.Worksheet excelWorksheet = 
     (Excel.Worksheet)excelSheets.get_Item(currentSheet); 

// access cell within sheet 
    Excel.Range excelCell = 
     (Excel.Range)excelWorksheet.get_Range("A1", "A1"); 

Hope this helps

MDSN thông tin here

+0

nó chỉ hoạt động với .Visible = True. Làm thế nào về với .Visible = False? – Denis

3

gì về một cái gì đó như thế này: (chưa được kiểm tra)

//using Excel = Microsoft.Office.Interop.Excel; 

Excel.ApplicationClass app = new Excel.ApplicationClass(); 
Excel.Workbook workbook = app.Workbooks.Open("YourFile.xls", 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Number 3"]; 
worksheet.Activate(); 
+0

điều này làm việc cho tôi :) – Somebody

+0

chỉ hoạt động nếu .Visible = True – Denis

+0

Ai đó có thể vui lòng xác nhận @Denis – Si8

1

Nếu muốn trình bày ý kiến ​​phản hồi thị giác cho người dùng, hai câu lệnh này sẽ đặt bảng kích hoạt và se lect phạm vi cho phù hợp:

xem xét bao gồm các tuyên bố sau ngay trước khi khởi tạo Excel.Range ...

// Đặt tấm Hoạt động trong Excel

excelWorksheet.Activate()

Cũng hãy xem xét tuyên bố sau ngay lập tức sau khi khởi tạo Excel.Range ...

// Đặt phạm vi hoạt động trong Excel

excelCell.Activate()

0
public static Workbook openExternalWorkBook(String fileName) 
    { 
     Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();    
     excel.Visible = false; 
     return excel.Workbooks.Open(fileName, false); 
    } 
Các vấn đề liên quan