使用C#将数据从excel文件中导出实例代码
使用C#讲数据从excel文件中导出实例代码如下:
- private void doExport(DataSet ds1,string[] str)
- {
- System.Reflection.Missing oMissing = System.Reflection.Missing.Value;
- _Application xlApp = null;
- _Workbook xlWorkbook = null;
- _Worksheet xlWorksheet = null;
- try
- {
- xlApp = new ApplicationClass();
- xlApp.Visible = true;
- xlWorkbook = xlApp.Workbooks.Add(oMissing);
- xlWorksheet = xlWorkbook.Worksheets.Add(oMissing, oMissing, 1, oMissing) as _Worksheet;
- xlWorksheet.Name = "福州市盲人易做图单位信息";
- Excel.Range r;
- r = xlWorksheet.get_Range(xlWorksheet.Cells[1, 1], xlWorksheet.Cells[1, 7]); //取得合并的区域
- xlWorksheet.get_Range(xlWorksheet.Cells[1, 1], xlWorksheet.Cells[1, 7]).Font.Size = 20;
- xlWorksheet.get_Range(xlWorksheet.Cells[1, 1], xlWorksheet.Cells[1, 7]).RowHeight = 45;
- xlWorksheet.get_Range(xlWorksheet.Cells[2, 1], xlWorksheet.Cells[2, 1]).ColumnWidth = 5;
- xlWorksheet.get_Range(xlWorksheet.Cells[2, 3], xlWorksheet.Cells[2, 3]).ColumnWidth = 33;
- xlWorksheet.get_Range(xlWorksheet.Cells[2, 6], xlWorksheet.Cells[2, 6]).ColumnWidth = 15;
- xlWorksheet.get_Range(xlWorksheet.Cells[2, 7], xlWorksheet.Cells[2, 7]).ColumnWidth = 50;
- r.MergeCells = true;
- r.HorizontalAlignment = Excel.Constants.xlCenter;
- xlWorksheet.Cells[1, 1] = "福州市盲人易做图单位信息";
- xlWorksheet.Cells[2, 1] = "ID";
- xlWorksheet.Cells[2, 2] = "单位编号";
- xlWorksheet.Cells[2, 3] = "单位名称";
- xlWorksheet.Cells[2, 4] = "单位类型";
- xlWorksheet.Cells[2, 5] = "负责人";
- xlWorksheet.Cells[2, 6] = "联系电话";
- xlWorksheet.Cells[2, 7] = "联系地址";
-
- for (int i = 0; i < ds1.Tables[0].Rows.Count; i )
- {
- xlWorksheet.Cells[i 3, 1] = i 1;
- xlWorksheet.Cells[i 3, 2] = ds1.Tables[0].Rows[i][1].ToString();
- xlWorksheet.Cells[i 3, 3] = ds1.Tables[0].Rows[i][2].ToString();
- xlWorksheet.Cells[i 3, 4] = ds1.Tables[0].Rows[i][3].ToString();
- xlWorksheet.Cells[i 3, 5] = ds1.Tables[0].Rows[i][4].ToString();
- xlWorksheet.Cells[i 3, 6] = ds1.Tables[0].Rows[i][5].ToString();
- xlWorksheet.Cells[i 3, 7] = ds1.Tables[0].Rows[i][6].ToString();
-
- }
- xlWorkbook.SaveAs(Hiddenfield1.Value, oMissing, oMissing, oMissing, oMissing,
- oMissing, Excel.XlSaveAsAccessMode.xlShared, oMissing, oMissing, oMissing,
- oMissing, oMissing);
- xlApp.Quit();
- }
- catch
- {
- }
- finally
- {
- System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
- xlApp = null;
- GC.Collect();
- }
- }
- 格式控制
- xSt.get_Range(excel.Cells[1,1],excel.Cells[1,1]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//对齐方式
- xSt.get_Range(excel.Cells[1,1],excel.Cells[1,1]).Select();//设置选中的部分的颜色
- xSt.get_Range(excel.Cells[1,1],excel.Cells[1,1]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种
- xSt.get_Range(excel.Cells[1,1],excel.Cells[1,1]).Font.Bold = true;//字体类型
- xSt.get_Range(excel.Cells[1,1],excel.Cells[1,1]).Font.Size = 22;//字体大小
-
- xSt.get_Range("a1","a1").ColumnWidth = 20;//列宽度
- object oo = false;
- xSt.get_Range("A1","B1").Merge(oo);//合并单元格
补充:软件开发 , C# ,