C#操作excel打印

原文地址:https://www.cnblogs.com/pilgrim/p/6013207.html

using System;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private bool isStartPrint = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string OriginalPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\IMS.accdb";
            ////初始化數據庫
            //DataBase.OleDbObject.InitDatabase(OriginalPath);
            //DataBase.OleDbObject.OpenDb();
            //int k=DataBase.OleDbObject.Select("select * from ElementInventory").Rows.Count;

            //初始化要寫入Excel的數據
            DataTable dt = new DataTable();
            for (int i = 0; i < 11; i++)
            {
                DataColumn dc = new DataColumn();
                dc.ColumnName = "name" + i;
                dc.DataType = typeof(string);
                dt.Columns.Add(dc);
            }
            for (int i = 0; i < 30; i++)
            {
                DataRow dr = dt.NewRow();
                if (i % 2 == 0)
                {
                    dr[0] = "測試用例" + i + "號,開始測試是否自動換行,以及頁面高度自適應。";
                }
                else
                {
                    dr[0] = "測試用例" + i + "號";
                }
                for (int j = 1; j < 11; j++)
                {
                    dr[j] = j;
                }
                dt.Rows.Add(dr);
            }
            if (!isStartPrint)
            {
                Thread th = new Thread(delegate ()
                {
                    DataTabletoExcel(dt, "測試.xlsx");
                });
                th.Start();
                isStartPrint = true;
            }
            else
            {
                MessageBox.Show("打印程序已啓用,請稍後……", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            //DataTabletoExcel(dt, "測試.xlsx");
        }

        public void DataTabletoExcel(System.Data.DataTable dtTemp, string strFileName)
        {
            int rowNum = dtTemp.Rows.Count; //先得到dtTemp的行數
            int columnNum = dtTemp.Columns.Count; //列數
            Excel.Application ExcelApp = new Excel.Application(); //聲明一個應用程序類實例

            //ExcelApp.DefaultFilePath = ""; //默認文件路徑導出excel的路徑還是在參數strFileName裏設置
            //ExcelApp.DisplayAlerts = true;
            //ExcelApp.SheetsInNewWorkbook = 1;///返回或設置 Microsoft Excel 自動插入到新工作簿中的工作表數目。
            Excel.Workbook worksBook = ExcelApp.Workbooks.Add(); //創建一個新工作簿
            Excel.Worksheet workSheet = (Excel.Worksheet)worksBook.Worksheets[1]; //在工作簿中得到sheet。
            if (workSheet == null)
            {
                System.Diagnostics.Debug.WriteLine("ERROR: worksheet == null");
                return;
            }
            workSheet.Name = "測試Sheet1"; //工作表的名稱
            workSheet.Cells.WrapText = true; //設置所有列的文本自動換行
            workSheet.Cells.EntireRow.AutoFit(); //設置所有列自動調整行高
            #region 繪製列
            ///自定義方法,向sheet中繪製列
            RangeMark(workSheet, "A1", "A2", "合併豎列1");
            RangeMark(workSheet, "B1", "B2", "合併豎列2");
            RangeMark(workSheet, "C1", "C2", "合併豎列3");
            RangeMark(workSheet, "D1", "D2", "合併豎列4");
            RangeMark(workSheet, "E1", "E2", "合併豎列5");
            RangeMark(workSheet, "F1", "H1", "合併橫行1");
            RangeMark(workSheet, "F2", "F2", "合併橫行1.1");
            RangeMark(workSheet, "G2", "G2", "合併橫行1.2");
            RangeMark(workSheet, "H2", "H2", "合併橫行1.3");
            RangeMark(workSheet, "I1", "K1", "合併橫行2");
            RangeMark(workSheet, "I2", "J2", "合併橫行2.1");
            RangeMark(workSheet, "K2", "K2", "合併橫行2.2");
            #endregion
            //將DataTable中的數據導入Excel中
            for (int i = 0; i < rowNum; i++)
            {
                for (int j = 0; j < columnNum; j++)
                {
                    workSheet.Cells[i + 3, j + 1] = dtTemp.Rows[i][j].ToString(); //文本

                }
            }
            ///保存路徑
            string filePath = @"C:\Users\Admin\Desktop\" + strFileName;
            if (File.Exists(filePath))
            {
                try
                {
                    File.Delete(filePath);
                }
                catch (Exception)
                {

                }
            }
            ExcelApp.Visible = true;
            //------------------------打印頁面相關設置--------------------------------
            workSheet.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA4;//紙張大小
            workSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;//頁面橫向
                                                                                  //workSheet.PageSetup.Zoom = 75; //打印時頁面設置,縮放比例百分之幾
            workSheet.PageSetup.Zoom = false; //打印時頁面設置,必須設置爲false,頁高,頁寬纔有效
            workSheet.PageSetup.FitToPagesWide = 1; //設置頁面縮放的頁寬爲1頁寬
            workSheet.PageSetup.FitToPagesTall = false; //設置頁面縮放的頁高自動
            workSheet.PageSetup.LeftHeader = "Nigel";//頁面左上邊的標誌
            workSheet.PageSetup.CenterFooter = "第 &P 頁,共 &N 頁";//頁面下標
            workSheet.PageSetup.PrintGridlines = true; //打印單元格網線
            workSheet.PageSetup.TopMargin = 1.5 / 0.035; //上邊距爲2cm(轉換爲in)
            workSheet.PageSetup.BottomMargin = 1.5 / 0.035; //下邊距爲1.5cm
            workSheet.PageSetup.LeftMargin = 2 / 0.035; //左邊距爲2cm
            workSheet.PageSetup.RightMargin = 2 / 0.035; //右邊距爲2cm
            workSheet.PageSetup.CenterHorizontally = true; //文字水平居中
                                                           //------------------------打印頁面設置結束--------------------------------
                                                           ///http://blog.csdn.net/wanmingtom/article/details/6125599
            worksBook.PrintPreview(); //打印預覽
                                      //worksBook.PrintOutEx(); //直接打印
                                      //worksBook.Close(); //關閉工作空間
                                      //ExcelApp.Quit(); //退出程序
                                      //workSheet.SaveAs(filePath); //另存表
            KillProcess(ExcelApp); //殺掉生成的進程
            isStartPrint = false; //打印完畢
            GC.Collect(); //垃圾回收機制
        }
        /// <summary>
        /// 引用Windows句柄,獲取程序PID
        /// </summary>
        /// <param name="Hwnd"></param>
        /// <param name="PID"></param>
        /// <returns></returns>
        [DllImport("User32.dll")]
        public static extern int GetWindowThreadProcessId(IntPtr Hwnd, out int PID);
        /// <summary>
        /// 殺掉生成的進程
        /// </summary>
        /// <param name="AppObject">進程程對象</param>
        private static void KillProcess(Excel.Application AppObject)
        {
            int Pid = 0;
            IntPtr Hwnd = new IntPtr(AppObject.Hwnd);
            System.Diagnostics.Process p = null;
            try
            {
                GetWindowThreadProcessId(Hwnd, out Pid);
                p = System.Diagnostics.Process.GetProcessById(Pid);
                if (p != null)
                {
                    p.Kill();
                    p.Dispose();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("進程關閉失敗!異常信息:" + ex);
            }
        }

        /// <summary>
        /// 創建表頭單元格,包括合併單元格
        /// </summary>
        /// <param name="workSheet">工作表</param>
        /// <param name="startCell">單元格起始格編號</param>
        /// <param name="endCell">單元格結束編號</param>
        /// <param name="strText">單元格名稱</param>
        private static bool RangeMark(Excel.Worksheet workSheet, string startCell, string endCell, string strText)
        {
            //創建一個區域對象。第一個參數是開始格子號,第二個參數是終止格子號。比如選中A1——D3這個區域。
            Excel.Range range = (Excel.Range)workSheet.get_Range(startCell, endCell);
            if (range == null)
            {
                System.Diagnostics.Debug.WriteLine("ERROR: range == null");
                return false;
            }
            range.Merge(0); //合併方法,0的時候直接合併爲一個單元格
            range.Font.Size = 16; //字體大小
            range.Font.Name = "黑體"; //字體
            range.WrapText = true; //文本自動換行
            range.EntireRow.AutoFit(); //自動調整行高
                                       //range.RowHeight = 20; 
                                       //range.EntireColumn.AutoFit(); //自動調整列寬
            range.ColumnWidth = 15;
            range.HorizontalAlignment = XlVAlign.xlVAlignCenter; //橫向居中
            range.Value = strText; //合併單元格之後,設置其中的文本
            range.Interior.ColorIndex = 20; //填充顏色
            range.Cells.Borders.LineStyle = 1; //設置單元格邊框的粗細

            return true;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章