日期:2014-05-18 浏览次数:20460 次
public static void PrintExcel(DataTable dt) { if (dt.Rows.Count > 0) { Excel.Application ExcelApp = new Excel.Application(); ExcelApp.Visible = true; Excel.Workbooks workbooks = ExcelApp.Workbooks; Excel._Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); Excel.Sheets sheets = workbook.Worksheets; Excel._Worksheet worksheet = (Excel._Worksheet)sheets.get_Item(1); int intColumnsCount = dt.Columns.Count; Excel.Range range_data = null; int iRow = 5; string strExcelBeginColumn = "A"; string strExcelEndColumn = string.Empty; int a = intColumnsCount / 26; if (a > 0) { string strFirstKey = ((char)(65 + (a - 1))).ToString(); int b = intColumnsCount % 26; string strLastKey = ((char)(65 + (b - 1))).ToString(); if (b == 0) { strLastKey = "Z"; if (strFirstKey == "A") { strFirstKey = string.Empty; } else { strFirstKey = ((char)(65 + (a - 2))).ToString(); } } strExcelEndColumn = strFirstKey + strLastKey; } else { strExcelEndColumn = ((char)(65 + (intColumnsCount - 1))).ToString(); } object[] objColumnsHeaderText = new object[intColumnsCount]; object[] objData = new object[intColumnsCount]; for (int i = 0; i < dt.Columns.Count; i++) { objColumnsHeaderText[i] = dt.Columns[i].ColumnName.ToString(); } range_data = worksheet.get_Range(strExcelBeginColumn + iRow.ToString().Trim(), strExcelEndColumn + iRow.ToString().Trim()); range_data.Font.Size = 10; range_data.Value2 = objColumnsHeaderText; range_data.Font.Bold = true; range_data.Rows.HorizontalAlignment = HorizontalAlign.Center; range_data.Borders.LineStyle = 1; for (int i = 0; i < dt.Rows.Count; i++) { iRow++; for (int j = 0; j < intColumnsCount; j++) { if (dt.Rows[i][j] != null) { objData[j] = dt.Rows[i][j].ToString().Trim(); } else {