using System; using System.Collections.Generic; using System.Text; using System.Data; namespace Personal { public class Print { /// <summary> /// 将DataTabl内容打印出来 /// Table 表, strHead 表名,Zoom 缩放比% /// </summary> private void baobiao(DataTable Table, string strHead, sbyte Zoom) { try { Excel.Application excelKccx = new Excel.Application(); //创建excel对象 Excel._Workbook xBk; Excel._Worksheet xSt; xBk = excelKccx.Workbooks.Add(true); xSt = (Excel._Worksheet)xBk.ActiveSheet; Excel.Range range = xSt.get_Range(excelKccx.Cells[1, 1], excelKccx.Cells[1, 22]); range.ClearContents();//先把Range内容清除,合并才不会出错 range.MergeCells = true; range.Value2 = strHead;//"普通医保住院定额超支管理报表(一般住院)"; range.Font.Bold = true; range.Font.Size = 15; range.Font.ColorIndex = 4;//颜色 range.HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; //设置标题格式为居中对齐 // 设置表头 int row = 2; for (int i = 0; i < Table.Columns.Count; i++)//取字段名 { excelKccx.Cells[row, i + 1] = Table.Columns[i].ColumnName.ToString(); xSt.get_Range(excelKccx.Cells[row, i + 1], excelKccx.Cells[row, i + 1]).Interior.ColorIndex = 5; } xSt.get_Range(excelKccx.Cells[row, 1], excelKccx.Cells[row, Table.Columns.Count]).EntireColumn.AutoFit();//自动调整列宽 xSt.get_Range(excelKccx.Cells[row, 1], excelKccx.Cells[row, Table.Columns.Count]).Font.Bold = true; for (int i = 0; i < Table.Rows.Count; i++)//取记录值 { row++; for (int j = 0; j < Table.Columns.Count; j++) { excelKccx.Cells[row, j + 1] = Table.Rows[i][j].ToString(); } } excelKccx.Visible = true; object oMissing = System.Reflection.Missing.Value; xSt.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA3;//设置纸张大小 xSt.PageSetup.Zoom = Zoom; //缩放比例 xSt.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;//横向打印 xlPortrait1-纵向,2-横向; xSt.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); xBk.PrintOut(oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); // 打印: // xBk.PrintPreview(oMissing);//打印预览 xBk.Close(null, null, null); excelKccx.Workbooks.Close(); excelKccx.Application.Quit(); excelKccx.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelKccx); GC.Collect();//强行销毁 } catch { GC.Collect();//强行销毁 }; } } }