日期:2014-05-18 浏览次数:20801 次
public void printAll(System.Data.DataTable dt, string SheetName) { //手动设置 int startrow = 2;//开始写数据的行数,写Datatable数据 int iRows = 0; int iCols = 0; int iTrueCols = 0; Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(System.Reflection.Missing.Value); Microsoft.Office.Interop.Excel.Worksheet ws = null; if (wb.Worksheets.Count > 0) { ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1); } else { wb.Worksheets.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value); ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1); } if (ws != null) { if (SheetName.Trim() != "") { ws.Name = SheetName; } iRows = dt.Rows.Count; iTrueCols = dt.Columns.Count; //包含隐藏的列,一共有多少列 iCols = dt.Columns.Count; string[,] dimArray = new string[iRows + 1, iCols]; for (int j = 0, k = 0; j < iTrueCols; j++) { dimArray[0, k] = dt.Columns[j].Caption ; k++; } for (int i = 0; i < iRows; i++) { for (int j = 0, k = 0; j < iTrueCols; j++) { dimArray[i + 1, k] = dt.Rows[i][j].ToString(); k++; } } ws.get_Range(ws.Cells[startrow, 1], ws.Cells[iRows + startrow, iCols]).Value2 = dimArray; ws.get_Range(ws.Cells[startrow, 1], ws.Cells[startrow, iCols]).Font.Bold = true; ws.get_Range(ws.Cells[startrow, 1], ws.Cells[iRows + startrow, iCols]).Font.Size = 10.0; ws.get_Range(ws.Cells[startrow, 1], ws.Cells[iRows + startrow, iCols]).RowHeight = 14.25; ws.Columns.ColumnWidth =20; app.Cells[1, 2] = "库存报表"; //app.Cells[1, 5] = "日期: " + when.ToShortDateString(); ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 3]).Font.Size = 20.0; ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 3]).Font.Color = ColorTranslator.ToOle(Color.Red); } //设置禁止弹出保存和覆盖的询问提示框 app.DisplayAlerts = true; app.AlertBeforeOverwriting = false; app.Visible = true; //app.Save("aaaa"); }