//生成Excel文件,以便打印 private void button1_Click(object sender, System.EventArgs e) { int i = 0, j = 0; useExcel = true; excelApp = new Excel.ApplicationClass(); Excel.Workbook excelBook = excelApp.Workbooks.Add(1); Excel.Worksheet excelSheet = (Excel.Worksheet)excelBook.Worksheets[1]; if (conn.ds.Tables[0].Rows.Count == 0) { MessageBox.Show("无可打印内容!", "提醒!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } try { //设置表头 excelSheet.Cells[1, 1] = comboBox_School.Text + ":" + comboBox_Class_Type.Text + "-" + conn.Class_IDtoWhat(comboBox_Class.SelectedValue.ToString(), "Class_Name"); excelSheet.Cells[2, 1] = "身份证号码"; excelSheet.Cells[2, 2] = "姓名"; excelSheet.Cells[2, 3] = "性别"; excelSheet.Cells[2, 4] = "出生日期"; excelSheet.Cells[2, 5] = "父亲"; excelSheet.Cells[2, 6] = "母亲"; excelSheet.Cells[2, 7] = "监护人"; excelSheet.Cells[2, 8] = "联系电话"; excelSheet.Cells[2, 9] = "家庭住址"; excelSheet.Cells[2, 10] = "父亲职业"; excelSheet.Cells[2, 11] = "父亲学历"; excelSheet.Cells[2, 12] = "母亲职业"; excelSheet.Cells[2, 13] = "母亲学历"; excelSheet.Cells[2, 14] = "区县"; excelSheet.Cells[2, 15] = "办事处"; excelSheet.Cells[2, 16] = "居委会"; //设置报表表头格式 excelSheet.get_Range(excelSheet.Cells[2, 1], excelSheet.Cells[2, 16]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; excelSheet.get_Range(excelSheet.Cells[2, 1], excelSheet.Cells[2, 16]).Font.Bold = true; string str_Sql = "SELECT Student_ID As 身份证号码,Name As 姓名,Sex AS 性别,convert(char(10),Birthday,120) As 出生日期,Father AS 父亲,Mother AS 母亲,Keeper AS 监护人,StudentTel AS 联系电话,Student_Address AS 家庭住址,Father_Job AS 父亲职业,Father_XueLi AS 父亲学历,Mother_Job AS 母亲职业,Mother_XueLi AS 母亲学历,QuXian_Name AS 区县,Office_Name AS 办事处,Committee_Name AS 居委会 FROM View_StudentClass_Detail_City4 WHERE Class_ID=" + comboBox_Class.SelectedValue + " AND School_ID='" + comboBox_School.SelectedValue.ToString() + "'"; conn.Fill(str_Sql); DataGrid1.SetDataBinding(conn.ds, "TableIn"); //填充表中各单元格 for (i = 1; i <= conn.ds.Tables[0].Rows.Count; i++) { for (j = 1; j <= conn.ds.Tables[0].Columns.Count; j++) { excelSheet.Cells[i + 2, j] = "'" + conn.ds.Tables[0].Rows[i - 1][j - 1].ToString(); } } excelSheet.get_Range(excelSheet.Cells[1, 1], excelSheet.Cells[i + 1, j]).Select(); excelSheet.get_Range(excelSheet.Cells[1, 1], excelSheet.Cells[i + 1, j]).Columns.AutoFit(); excelApp.Visible = true; } catch { throw new Exception("Excel error"); } }