手机版

C中数据导出到Excel表格(4)

时间:2025-07-07   来源:未知    
字号:

DataGridView 数据导出到Excel

24. if (ds.Tables[0].Rows.Count == 0)

25. {

26. MessageBox.Show("数据集为空");

27. }

28. Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();

29. Workbook xlbook = xlapp.Workbooks.Add(true);

30. Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];

31. Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1,

ds.Tables[0].Columns.Count]);

32. range.MergeCells = true;

33. xlapp.ActiveCell.FormulaR1C1 = ReportName;

34. xlapp.ActiveCell.Font.Size = 20;

35. xlapp.ActiveCell.Font.Bold = true;

36. xlapp.ActiveCell.HorizontalAlignment =

Microsoft.Office.Interop.Excel.Constants.xlCenter;

37. int colIndex = 0;

38. int RowIndex = 2;

39. //开始写入每列的标题

40. foreach (DataColumn dc in ds.Tables[0].Columns)

41. {

42. colIndex++;

43. xlsheet.Cells[RowIndex, colIndex] = dc.Caption;

44. }

45. //开始写入内容

46. int RowCount = ds.Tables[0].Rows.Count;//行数

47. for (int i = 0; i < RowCount; i++)

48. {

49. RowIndex++;

50. int ColCount = ds.Tables[0].Columns.Count;//列数

51. for (colIndex = 1; colIndex <= ColCount; colIndex++)

52. {

53. xlsheet.Cells[RowIndex, colIndex] = ds.Tables[0].Rows[i][colIndex - 1];//dg[i,

colIndex - 1];

C中数据导出到Excel表格(4).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
×
二维码
× 游客快捷下载通道(下载后可以自由复制和排版)
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能出现无法下载或内容有问题,请联系客服协助您处理。
× 常见问题(客服时间:周一到周五 9:30-18:00)