Có ai có bất kỳ ý tưởng làm thế nào để in một tập tin excel lập trình bằng cách sử dụng C# và Excel Interop? Nếu vậy, bạn có thể vui lòng cung cấp mã không?In Excel bằng cách sử dụng Interop
13
A
Trả lời
20
Để in, bạn có thể sử dụng phương thức Worksheet.PrintOut(). Bạn có thể bỏ qua bất kỳ hoặc tất cả các đối số tùy chọn bằng cách đi qua trong Type.Missing. Nếu bạn bỏ qua tất cả chúng, nó sẽ mặc định in ra một bản sao từ máy in hoạt động của bạn. Nhưng bạn có thể sử dụng các đối số để đặt số lượng bản sao để in, đối chiếu, v.v. Xem trợ giúp về phương pháp Worksheet.PrintOut() để biết thêm.
Ví dụ họ hiển thị trong tập tin trợ giúp là:
private void PrintToFile()
{
// Make sure the worksheet has some data before printing.
this.Range["A1", missing].Value2 = "123";
this.PrintOut(1, 2, 1, false, missing, true, false, missing);
}
Nhưng trừ khi bạn cần thay đổi các thiết lập mặc định, bạn chỉ có thể vượt qua trong Type.Missing cho tất cả các đối số. Dưới đây là ví dụ sử dụng tự động hóa để mở Sổ làm việc Excel, in trang đầu tiên và sau đó tắt:
void PrintMyExcelFile()
{
Excel.Application excelApp = new Excel.Application();
// Open the Workbook:
Excel.Workbook wb = excelApp.Workbooks.Open(
@"C:\My Documents\Book1.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);
// Get the first worksheet.
// (Excel uses base 1 indexing, not base 0.)
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
// Print out 1 copy to the default printer:
ws.PrintOut(
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Cleanup:
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(ws);
wb.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wb);
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
}
Hy vọng điều này sẽ hữu ích!
Mike
1
cải thiện quan trọng là mã cho chọn máy in, ví dụ:
var printers = System.Drawing.Printing.PrinterSettings.InstalledPrinters;
int printerIndex = 0;
foreach(String s in printers)
{
if (s.Equals("Name of Printer"))
{
break;
}
printerIndex++;
}
xlWorkBook.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing,printers[printerIndex], Type.Missing, Type.Missing, Type.Missing);
cảm ơn bạn rất nhiều !!! điều này rất hữu ích! – yeahumok
Tuyệt vời, vui vì tôi có thể giúp. :-) –
bạn sẽ không biết làm thế nào để hiển thị một cuộc đối thoại in thay vì ngay lập tức in ấn tài liệu ... sẽ ya? – yeahumok