Excel导入导出数据库02

excel导入时还要保存字体、其背景颜色等信息时读取方法就要改变:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.IO;
  6 using System.Data.OleDb;
  7 using System.Data;
  8 using Microsoft.Office.Interop.Excel;
  9 using System.Reflection;
 10 using System.Runtime.InteropServices;
 11
 12 namespace WinOrderAd
 13 {
 14     public class Excel
 15     {
 16         public string FilePath
 17         {
 18             get;
 19             set;
 20         }
 21         public Dictionary<string, string> FiledNames
 22         {
 23             get;
 24             set;
 25         }
 26         public Excel()
 27         {
 28         }
 29
 30         public DataSet ImportExcel()//若只需要知道数据就用此方法
 31         {
 32
 33             try
 34             {
 35                 string strConn;
 36                 if (Path.GetExtension(FilePath) == ".xlsx")
 37                     strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
 38                 else
 39                     strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
 40                 OleDbConnection OleConn = new OleDbConnection(strConn);
 41                 OleConn.Open();
 42                 System.Data.DataTable table = OleConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
 43                 DataSet OleDsExcle = new DataSet();
 44                 for (int i = 0; i < table.Rows.Count; i++)
 45                 {
 46                     string tableName = table.Rows[i]["Table_Name"].ToString();
 47                     tableName = tableName.Replace("'", "");
 48                     if (tableName.EndsWith("$"))
 49                     {
 50                         string sql = "SELECT * FROM [" + tableName + "]";
 51                         OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
 52                         OleDaExcel.Fill(OleDsExcle, tableName);
 53                         OleConn.Close();
 54                     }
 55                 }
 56                 return OleDsExcle;
 57             }
 58             catch (Exception err)
 59             {
 60                 throw err;
 61             }
 62         }
 63
 64
 65         /// <summary>
 66         /// 用Excel Com组件方式读取Excel内容到DataSet(兼容性较高)
 67         /// </summary>
 68         /// <param name="path"></param>
 69         /// <returns></returns>
 70         public DataSet ToDataTableEx()
 71         {
 72             Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
 73
 74             excel.Visible = false;
 75             excel.ScreenUpdating = false;
 76             excel.DisplayAlerts = false;
 77
 78             excel.Workbooks.Add(FilePath);
 79             Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
 80             Range rangecell = null;
 81             DataSet ds = new DataSet();
 82             try
 83             {
 84                 //遍历Worksheets中的每张表
 85                 for (int i = 1; i <= excel.Worksheets.Count; i++)
 86                 {
 87                     //获得指定表
 88                     worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.Worksheets[i];
 89
 90                     System.Data.DataTable dt = new System.Data.DataTable();
 95
 96                     //取表明赋值到dt TableName
 97                     dt.TableName = worksheet.Name;
 98
 99                     worksheet.Columns.EntireColumn.AutoFit();
100
101                     int row = worksheet.UsedRange.Rows.Count;
102                     int col = worksheet.UsedRange.Columns.Count;
103
104                     for (int c = 1; c <= col; c++)
105                     {
106                         dt.Columns.Add(new DataColumn((String)((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, c]).Text));
107                     }
108                     //添加一样式列
109                     dt.Columns.Add(new DataColumn("Style"));
110
111                     for (int r = 2; r <= row; r++)
112                     {
113                         DataRow newRow = dt.NewRow();
114                         for (int c = 1; c <= col; c++)
115                         {
116                             rangecell = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r, c];
117                             newRow[c - 1] = rangecell.Text;
118                             if (c == 3)
119                             {
120                                 //取信息的字体颜色与背景颜色
121                                 newRow[col] = rangecell.Font.Color + "|" + rangecell.Interior.Color;
122                             }
123                         }
124                         dt.Rows.Add(newRow);
125                     }
126                     ds.Tables.Add(dt);
127                 }
128             }
129             catch (Exception ex)
130             {
131                 throw (ex);
132             }
133             finally
134             {
135                 if (worksheet != null)
136                 {
137                     System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
138                     worksheet = null;
139                     System.Runtime.InteropServices.Marshal.ReleaseComObject(rangecell);
140                     rangecell = null;
141                 }
142                 excel.Workbooks.Close();
143                 excel.Quit();
144                 int generation = System.GC.GetGeneration(excel);
145                 if (excel != null)
146                 {
147                     System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
148                     excel = null;
149                 }
150                 System.GC.Collect(generation);
151             }
152             return ds;
153         }
154
341
342     }
343 }

导出设置其样式

  1  public void ExportExcel(string[] listTableName, string[] listColName, List<List<Ad>> resource, string exporFilePath)
  2         {
  3             List<Ad> list = null;
  4             List<Ad> listresource = null;
  5             Microsoft.Office.Interop.Excel.Application app =
  6                new Microsoft.Office.Interop.Excel.ApplicationClass();
  7
  8             app.Visible = false;
  9             app.ScreenUpdating = false;
 10             app.DisplayAlerts = false;
 11             Workbook wBook = app.Workbooks.Add(true);
 12
 13             InsertLinkWorksheet(app, wBook);
 14
 15             Worksheet wSheet = null;
 16             Range rangeResource = null;
 17             Range rangeContent = null;
 18             Range rangeTitle = null;
 19             //for (int k = 0; k < listList.Count; k++)
 20             for (int k = listList.Count - 1; k >= 0; k--)
 21             { 23                 listresource = resource[k];//已排好的数据
 24                 wSheet = wBook.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Worksheet;
 25                 wSheet.Name = listTableName[k];
 26
 27                 try
 28                 {
 29                     int resourcenum = listresource.Count;
 30                     if (resourcenum > 0)
 31                     {
 32                         for (int i = 0; i < resourcenum; i++)
 33                         {
 34                             wSheet.Cells[i + 2, 1] = (i + 1);
 35                             wSheet.Cells[i + 2, 2] = listresource[i].ID;
 36                             wSheet.Cells[i + 2, 3] = listresource[i].Info;
 37                             wSheet.Cells[i + 2, 4] = listresource[i].Format;
 38                             wSheet.Cells[i + 2, 5] = listresource[i].Times;
 39                             wSheet.Cells[i + 2, 6] = listresource[i].Attach;
 40                             wSheet.Cells[i + 2, 7] = listresource[i].Frequency;
 41                             wSheet.Cells[i + 2, 8] = listresource[i].Same;
 42                             wSheet.Cells[i + 2, 9] = listresource[i].Dif;
 43                             wSheet.Cells[i + 2, 10] = listresource[i].Balanced;
 44
 45                             if (listresource[i].RowStyle.Split('|')[0] != "")
 46                             {
 47                                 rangeResource = wSheet.get_Range(wSheet.Cells[i + 2, 1], wSheet.Cells[i + 2, 10]);
 48                                 rangeResource.Font.Color = listresource[i].RowStyle.Split('|')[0];
 49                                 rangeResource.Interior.Color = listresource[i].RowStyle.Split('|')[1];
 50                             }
 51                         }
 52                     }
 53  78                     int m = 0;
 79                     int col = listColName.Count();
 80                     for (m = 0; m < col; m++)
 81                     {
 82                         string headname = listColName[m];//单元格头部
 83                         wSheet.Cells[1, 1 + m] = headname;
 84                     }
 85                     //内容
 86                     rangeContent = wSheet.get_Range(wSheet.Cells[2, 1], wSheet.Cells[list.Count + resourcenum + 2 + 1, col]);
 87                     rangeContent.Borders.Color = System.Drawing.Color.Black.ToArgb();
 88                     //rangeContent.Interior.Color = 10092543;    //设置区域背景色
 89                     rangeContent.VerticalAlignment = -4108;//竖向居中
 90                     rangeContent.HorizontalAlignment = -4108;//横向居中
 91                     rangeContent.RowHeight = 18;
 92                     rangeContent.EntireColumn.AutoFit();//自动调整列宽
 93                     //标题
 94                     rangeTitle = wSheet.get_Range(wSheet.Cells[1, 1], wSheet.Cells[1, col]);
 95                     rangeTitle.Borders.Color = System.Drawing.Color.Black.ToArgb();
 96                     rangeTitle.Interior.Color = 65280;    //设置区域背景色
 97                     rangeTitle.VerticalAlignment = -4108;
 98                     rangeTitle.HorizontalAlignment = -4108;
 99                     rangeTitle.RowHeight = 18;
100                     rangeTitle.EntireColumn.AutoFit();
101                     //冻结首行
102                     //rangeTitle.Select();
103                     app.ActiveWindow.SplitColumn = 0;
104                     app.ActiveWindow.SplitRow = 1;
105                     app.ActiveWindow.FreezePanes = true;
106                     //rangeTitle.Font.Bold = true;    //设置字体粗体。
107                 }
108                 catch (Exception err)
109                 {
110                     throw err;
111                 }
112                 finally
113                 {
114
115                 }
116             }
117             //设置禁止弹出保存和覆盖的询问提示框
118             app.DisplayAlerts = false;
119             app.AlertBeforeOverwriting = false;
120             ((Worksheet)wBook.Worksheets["Sheet1"]).Delete();
121             try
122             {
123                 wBook.Saved = true;
124                 //保存工作簿
125                 System.Reflection.Missing miss = System.Reflection.Missing.Value;
126                 wBook.SaveAs(exporFilePath, miss, miss, miss, miss, miss, XlSaveAsAccessMode.xlNoChange, miss, miss, miss, miss, miss);
127             }
128             catch (Exception ex)
129             {
130                 throw ex;
131             }
132
133             if (rangeResource != null)
134             {
135                 System.Runtime.InteropServices.Marshal.ReleaseComObject(rangeResource);
136                 System.Runtime.InteropServices.Marshal.ReleaseComObject(rangeContent);
137                 System.Runtime.InteropServices.Marshal.ReleaseComObject(rangeTitle);
138                 rangeResource = null;
139                 rangeContent = null;
140                 rangeTitle = null;
141             }
142
143             if (wSheet != null)
144             {
145                 System.Runtime.InteropServices.Marshal.ReleaseComObject(wSheet);
146                 wSheet = null;
147             }
148
149             if (wBook != null)
150             {
151                 System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook);
152                 wBook = null;
153             }
154             app.Workbooks.Close();
155             app.Quit();
156             int generation = System.GC.GetGeneration(app);
157             if (app != null)
158             {
159                 System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
160                 app = null;
161             }
162             GC.Collect(generation);
163         }

listTableName为多个sheet的名称

listColName为每页的列名

resource为sheet数据队列

exporFilePath为要保存的路径

时间: 2024-08-22 15:14:26

Excel导入导出数据库02的相关文章

excel导入导出问题ooo11

问题描述 咨询一下各位大虾,我在做excel导入导出的时候,总数不成功,麻烦帮忙指教啊,谢谢了.代码如下:///<summary>///将DataSet数据导出到Excel,DataSet数据从数据库读取///</summary>///<paramname="ds">DataSet数据源</param>publicvoidExportToExcel(DataSetds){//TbBindData是一个集合,通过excel导入进来intin

Oracle导入导出数据库的语法

    导读:oracle中除了在Oracle编辑器中用图形化的方式导入导出文理文件的数据方式外,还可以采用命令行的方式导入导出数据库,其语法实示例如下:    imp [username[/password[@service]]]    步骤:1.首先在进入 dos, 然后切换到 oracle 数据库物理文件所在的目录即(dmp文件所在的目录).接下来输入下述语句!    imp username/password@service file=psmis.dmp fromuser=psmis t

ASP.NETR把Excel导入SQL数据库的自定义类

ASP.NETR把Excel导入SQL数据库的自定义类 以下是引用片段:public class SaveToSql {   public string strNewCodeId = string.Empty;   public string strNewCode = string.Empty;   public string strNewDes = string.Empty;   public string strOldCodeId = string.Empty;   public strin

Excel导入ACCESS数据库动画教程

<Excel2003入门动画教程62.Excel导入ACCESS数据库>. 演示动画 操作步骤 Excel可以从其它文档中批量导入数据,下面我们将一个ACCESS数据库中的数据表导入到Excel中: 在Excel中,执行"数据→导入外部数据→导入数据"命令,打开"选取数据源"对话框,定位到需要导入数据的文件所在的文件夹,选中相应的文件,单击"打开"按钮,打开"导入数据"对话框,选择保存数据的第一个单元格,按下&qu

用c#语言怎么写导入导出数据库程序

问题描述 用c#语言怎么写导入导出数据库程序 解决方案 解决方案二:http://blog.csdn.net/yunhaiC/archive/2008/10/23/3132179.aspx

excel导入导出组件设计

这是我设计的excel导入导出组件,使用Java 编写,通过xml文件的配置,来设置excel到java bean的映射.关键(配置)文件:ExcelModeMappingl.xml. 之前一直为excel的导入导出烦恼,每写一次都感觉是"重复造轮子",代码很繁琐,可移植性特别差.终于下决心写一个可重用性很高的组件,专门解决"重复造轮子"的问题.   xml配置文件名称:ExcelModeMappingl.xml 内容(示例): <?xml version=&

请教EXCEL导入sqlserver数据库

问题描述 现在我可以将EXCEL导入到数据库里面去(单表操作)但是现在需求是要做成通用的就是在页面上选择表名(或者从EXCEL文件里面获取到表明)就将数据导入到那张表里去像这样的多表操作我就没了思路请各位指导!!! 解决方案 解决方案二:都差不多.只是中间多了一个创建表的过程.将表名,表的字段,类型都取出来,创建表.然后放入数据库解决方案三:求解啊!!!解决方案四:都差不多.只是中间多了一个创建表的过程.将表名,表的字段,类型都取出来,创建表.然后放入数据库解决方案五:每次得到的Excel还有插

mysql 添加用户,授权,远程登陆,远程导入导出数据库,用户及权限查询,新增用户无法登陆,

首先提示一点,当使用新增用户登陆失败: root@controller:~# mysql -h localhost -ukeystone -ppassword  ERROR 1045 (28000): Access denied for user 'keystone'@'localhost' (using password: YES)解决方法:  增加普通用户后,执行:  mysql> use mysql mysql> delete from user where user=''; mysql

swing-请问:用SWING容器怎么实现excel导入导出mysql里?谢谢!!!

问题描述 请问:用SWING容器怎么实现excel导入导出mysql里?谢谢!!! 也可以不用SWING容器,只要能使用excel批量导入导出mysql 解决方案 这个就是数据的读取和存储吧,一般使用jxl包来进行读取,参考下这个http://www.bkjia.com/ASPjc/892365.html