C# DataTable WriteToExcel

1:帮助类

  1 public class ExcelHander
  2     {
  3         private string AList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  4         private Workbook m_objBook;
  5         private Workbooks m_objBooks;
  6         private Application m_objExcel;
  7         private Missing miss = Missing.Value;
  8         public static Missing MissValue = Missing.Value;
  9         private Worksheet sheet;
 10
 11         public void CloseExcelApplication()
 12         {
 13             try
 14             {
 15                 foreach (Process process in Process.GetProcessesByName("excel"))
 16                 {
 17                     process.Kill();
 18                 }
 19             }
 20             catch (Exception exception)
 21             {
 22                 throw new Exception(exception.Message + exception.StackTrace, exception.InnerException);
 23             }
 24         }
 25
 26         public void CreateExceFile()
 27         {
 28             this.m_objExcel = new ApplicationClass();
 29             this.UserControl(false);
 30             this.m_objBooks = this.m_objExcel.Workbooks;
 31             this.m_objBook = this.m_objBooks.Add(this.miss);
 32             this.sheet = (Worksheet)this.m_objBook.ActiveSheet;
 33         }
 34
 35         public string GetAix(int x, int y)
 36         {
 37             char[] chArray = this.AList.ToCharArray();
 38             if (x >= 0x1a)
 39             {
 40                 return "";
 41             }
 42             string str = "";
 43             return (str + chArray[x - 1].ToString() + y.ToString());
 44         }
 45
 46         public Range getRange(int x1, int y1, int x2, int y2)
 47         {
 48             return this.sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2));
 49         }
 50
 51         public object getValue(int x, int y)
 52         {
 53             return this.sheet.get_Range(this.GetAix(x, y), this.miss).Cells.get_Value(Missing.Value);
 54         }
 55
 56         public void insertRow(int y)
 57         {
 58             Range range = this.sheet.get_Range(this.GetAix(1, y), this.GetAix(0x19, y));
 59             range.Copy(this.miss);
 60             range.Insert(XlDirection.xlDown, this.miss);
 61             range.get_Range(this.GetAix(1, y), this.GetAix(0x19, y));
 62             range.Select();
 63             this.sheet.Paste(this.miss, this.miss);
 64         }
 65
 66         public void mergeCell(int x1, int y1, int x2, int y2)
 67         {
 68             this.sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2)).Merge(Missing.Value);
 69         }
 70
 71         public Worksheet NewSheet()
 72         {
 73             return (Worksheet)this.m_objBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
 74         }
 75
 76         public void OpenExcelFile(string filename)
 77         {
 78             this.m_objExcel = new ApplicationClass();
 79             this.UserControl(false);
 80             this.m_objExcel.Workbooks.Open(filename, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss, this.miss);
 81             this.m_objBooks = this.m_objExcel.Workbooks;
 82             this.m_objBook = this.m_objExcel.ActiveWorkbook;
 83             this.sheet = (Worksheet)this.m_objBook.ActiveSheet;
 84         }
 85
 86         public void past()
 87         {
 88             string link = "a,b,c,d,e,f,g";
 89             this.sheet.Paste(this.sheet.get_Range(this.GetAix(10, 10), this.miss), link);
 90         }
 91
 92         public void ReleaseExcel()
 93         {
 94             this.m_objExcel.Quit();
 95             Marshal.ReleaseComObject(this.m_objExcel);
 96             Marshal.ReleaseComObject(this.m_objBooks);
 97             Marshal.ReleaseComObject(this.m_objBook);
 98             Marshal.ReleaseComObject(this.sheet);
 99             GC.Collect();
100         }
101
102         public void SaveAs(string FileName)
103         {
104             this.m_objBook.SaveAs(FileName, this.miss, this.miss, this.miss, this.miss, this.miss, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, this.miss, this.miss, this.miss, this.miss);
105             this.m_objBook.Close(false, this.miss, this.miss);
106         }
107
108         public void setBorder(int x1, int y1, int x2, int y2, int Width)
109         {
110             this.sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2)).Borders.Weight = Width;
111         }
112
113         public void setValue(int x, int y, string text)
114         {
115             this.sheet.get_Range(this.GetAix(x, y), this.miss).set_Value(this.miss, text);
116         }
117
118         public void setValue(int x, int y, string text, System.Drawing.Font font, Color color)
119         {
120             this.setValue(x, y, text);
121             Range range = this.sheet.get_Range(this.GetAix(x, y), this.miss);
122             range.Font.Size = font.Size;
123             range.Font.Bold = font.Bold;
124             range.Font.Color = color;
125             range.Font.Name = font.Name;
126             range.Font.Italic = font.Italic;
127             range.Font.Underline = font.Underline;
128         }
129
130         public void UserControl(bool usercontrol)
131         {
132             if (this.m_objExcel != null)
133             {
134                 this.m_objExcel.UserControl = usercontrol;
135                 this.m_objExcel.DisplayAlerts = usercontrol;
136                 this.m_objExcel.Visible = usercontrol;
137             }
138         }
139
140         public Worksheet CurrentSheet
141         {
142             get
143             {
144                 return this.sheet;
145             }
146             set
147             {
148                 this.sheet = value;
149             }
150         }
151
152         public Workbook CurrentWorkBook
153         {
154             get
155             {
156                 return this.m_objBook;
157             }
158             set
159             {
160                 this.m_objBook = value;
161             }
162         }
163
164         public Workbooks CurrentWorkBooks
165         {
166             get
167             {
168                 return this.m_objBooks;
169             }
170             set
171             {
172                 this.m_objBooks = value;
173             }
174         }
175     }

2:实现方法

 1 public static void WirteToExcel()
 2         {
 3             if (ConfigReader.ReportTable.Rows.Count > 0)
 4             {
 5                 ExcelHander excelwirter = new ExcelHander();
 6                 int allNum = ConfigReader.ReportTable.Rows.Count;//统计下载总数
 7                 int resultfulNum = ConfigReader.ReportTable.Select("连接状态=‘有 效‘").Length;//有效的下载连接数
 8                 int errorNum = ConfigReader.ReportTable.Select("连接状态=‘无 效‘").Length;//无效的下载连接数
 9                 try
10                 {
11                     excelwirter.CreateExceFile();
12                     #region  写入细节
13                     int i = 1;
14                     int j = 1;
15                     foreach (var item in ConfigReader.ReportTable.Columns)
16                     {
17                         excelwirter.setValue(j, 1, ConfigReader.ReportTable.Columns[j - 1].ToString(), new System.Drawing.Font("TimesNewRoman", 12, FontStyle.Bold), Color.Black);
18                         j++;
19                     }
20                     i = 2;
21                     j = 1;
22                     foreach (DataRow dr in ConfigReader.ReportTable.Rows)
23                     {
24                         if (dr[2].ToString() == "无 效")
25                         {
26                             excelwirter.setValue(1, i, dr[0].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Red);
27                             excelwirter.setValue(2, i, dr[1].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Red);
28                             excelwirter.setValue(3, i, dr[2].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Red);
29                             excelwirter.setValue(4, i, dr[3].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Red);
30                         }
31                         else
32                         {
33                             excelwirter.setValue(1, i, dr[0].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Black);
34                             excelwirter.setValue(2, i, dr[1].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Black);
35                             excelwirter.setValue(3, i, dr[2].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Black);
36                             excelwirter.setValue(4, i, dr[3].ToString(), new System.Drawing.Font("TimesNewRoman", 10, FontStyle.Regular), Color.Black);
37                         }
38                         i++;
39                     }
40                     #endregion
41                     #region//写入汇总
42                     excelwirter.setValue(1, ++i, "下载总数:" + allNum.ToString(), new System.Drawing.Font("TimesNewRoman", 12, FontStyle.Bold), Color.Black);
43                     excelwirter.setValue(1, ++i, "连接状态正常数:" + resultfulNum.ToString(), new System.Drawing.Font("TimesNewRoman", 12, FontStyle.Bold), Color.Black);
44                     excelwirter.setValue(1, ++i, "连接异常数:" + errorNum.ToString(), new System.Drawing.Font("TimesNewRoman", 12, FontStyle.Bold), Color.Black);
45                     #endregion
46                     excelwirter.SaveAs(ConfigReader.WorkingPath + "report.xlsx");
47                 }
48                 catch (Exception)
49                 {
50                     Console.WriteLine("写入异常,请确定excel文件没有被独占");
51                 }
52                 finally
53                 {
54                     excelwirter.ReleaseExcel();
55                     excelwirter.CloseExcelApplication();
56                 }
57             }
58         }

时间: 2024-08-01 18:41:05

C# DataTable WriteToExcel的相关文章

将DataTable转换为List,将List转换为DataTable的实现类

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Xmh.DBUnit { /// <summary> /// 将DataTable转换为List,将

删除datatable中的行

今天遇到一问题,无论如何也删除不干净datatable.我想全部删除.但总是得不到想要的结果. for (int i = 0; i < dt.Rows.Count; i++) { //dt.Rows.Remove(dt.Rows[i]); dt.Rows[i].Delete(); Console.Write("dr.rows.count" + dt.Rows.Count + "\r\n删除了数据" + i.ToString() + "\r\n&quo

datatable

datatable添加数据 datatable dt=new datatable(); dt.columns.add("string");     //添加列 datarow dr=dt.newrow(); dr[0]="string"; dt.rows.add(dr);          //添加行

c# 之DataTable的扩展方法

由于太懒了,很久没更新了.毕业了,得好好装逼学习了,不能一心想着完了. 由于公司中的项目大量的使用DataTable,而每次对datatable进行操作的时候需要写很多相同的代码,所以秉着 装逼而学习 的态度,于是撸了几个扩展方法,记录下来,学习下.     class Program     {         public DataTable LinqTable = new DataTable();         void AddNewRow(int id, string name)   

ASP.Net的导出Excel的快速方法,DataTable导出Excel(亲测,非原创)

//使用方法 ExcelHelper.dataTableToCsv(dt,@"D:\1212.xls");System.Diagnostics.Process.Start(@"c:\1.xls"); //打开excel文件 public static void dataTableToCsv(DataTable table, string file) { string title = ""; FileStream fs = new FileStre

(转)在JAVA实现DataTable对象(三)——DataTable对象实现

大家都是行家,我就直接上代码了,我这个代码应该还是能看懂的,嘻嘻…. 1: import java.util.ArrayList; 2: import java.util.List; 3:   6:   7: public final class DataTable { 8:   9: private DataRowCollection rows; //用于保存DataRow的集合对象 10: private DataColumnCollection columns; //用于保存DataCol

几个和DataTable相关的函数

一.关于本文 本文中的DataTableHelper类包括了4个操作DataTable的函数,分别是 1)public static DataTable GetTestDataTable() 这是一个测试用的函数,生成一个有内容的DataTable 2)public static string PrintDataTable(DataTable dt) 这个函数向控制台打印一个DataTable中的所有内容 3)public static DataTable GetAnotherDataTable

List转Datatable 新方法

方法1,最简单的转换 DataTable dt = new DataTable(); dt.Columns.Add("id"); dt.Columns.Add("name"); dt.Rows.Add(new object[]{ 0,"顶层菜单"}); foreach (var cm in comdList) { DataRow dr = dt.NewRow(); dr["id"] = cm.SYS_COMMANDS_ID;

ExtAspNet从DataTable里导出Excel

protected void btn_ToExcel_Click(object sender, EventArgs e) { Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/excel"; Response.W