Hello World

C#(WINFORM, WINCE, WINDOWS MOBILE) 실전 활용 예제소스 및 프로그램 개발

[C#]엑셀 파일 출력 예제

댓글 0

C#

2021. 4. 2.

using Excel = Microsoft.Office.Interop.Excel;

private void ExcelFilePrint(string fileName)
{
   Excel.Application excelApp = new Excel.Application();

   // Open the Workbook:
   Excel.Workbook wb = excelApp.Workbooks.Open(
        fileName,
        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);

   int sheetcnt = wb.Worksheets.Count;

   // Get the first worksheet.
   // (Excel uses base 1 indexing, not base 0.)
   Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];

   /*
   ws.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4;//paper size
   ws.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;//Page horizontal
   ws.PageSetup.Zoom = 75; //page setting when printing, a few percent of the scale
   ws.PageSetup.Zoom = false; //Page setting when printing, must be set to false, page height, page width is valid
   ws.PageSetup.FitToPagesWide = 1; //Set the page width of the page to be 1 page wide
   ws.PageSetup.FitToPagesTall = false; //Set the page height of the page zoom automatically
   ws.PageSetup.CenterFooter = "Page &P page, &N page"; // page subscript
   ws.PageSetup.FooterMargin = 5;
   ws.PageSetup.PrintGridlines = false; //Print cell grid lines
   ws.PageSetup.TopMargin = 15; //The top margin is 2cm (converted to in)
   ws.PageSetup.BottomMargin = 20; //The bottom margin is 1.5cm
   ws.PageSetup.LeftMargin = 30; //The left margin is 2cm
   ws.PageSetup.RightMargin = 30; //The right margin is 2cm
   ws.PageSetup.CenterHorizontally = true; //Text horizontally centered
   */

   ws.PageSetup.Zoom = false;
   ws.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait;
   ws.PageSetup.CenterHorizontally = true;
   ws.PageSetup.FitToPagesWide = 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();

   System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ws);

   wb.Close(false, Type.Missing, Type.Missing);
   System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wb);

   excelApp.Quit();
   System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
}

엑셀 파일을 프린터 출력하는 예제 코드입니다.