Hello Mat

 找回密码
 立即注册
查看: 8052|回复: 0

C#读写EXCEL

[复制链接]

1294

主题

1520

帖子

110

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22633
发表于 2017-1-17 18:55:55 | 显示全部楼层 |阅读模式
C#读写EXCEL:【1】参考链接:http://www.open-open.com/code/view/1430553318349
【2】添加引用-COM组件-找到Excel-添加
【3】using Microsoft.Office.Interop.Excel;

读取Excel
  1. OpenFileDialog fileDialog = new OpenFileDialog();
  2.             fileDialog.ShowDialog();
  3.             string fileName = fileDialog.FileName;
  4.             DataSet ds = ReadExcel.ReadFromExcel(fileName);
  5.             object obj = ds.Tables[0].Rows[2][2];
复制代码
在 object obj处添加断点,可以查看数值
ReadExcel.ReadFromExcel函数如下:
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Data;
  9. using System.Data.OleDb;
  10. using System.IO;
  11. using System.Threading;
  12. using System.Windows;
  13. using System.Windows.Input;

  14. namespace Operate_Excel
  15. {
  16.     public class ReadExcel
  17.     {
  18.         private static DataSet dataSet = new DataSet();
  19.         private static List<string> tableList = new List<string>();
  20.         public static DataSet ReadFromExcel(string filePath)
  21.         {
  22.             dataSet.Clear();
  23.             tableList.Clear();
  24.             string errorMessage = string.Empty;
  25.             dataSet = GetExcelData(filePath, ref errorMessage);
  26.             return dataSet;
  27.         }
  28.         private static DataSet GetExcelData(string filePath, ref string errorMeg)
  29.         {
  30.             try
  31.             {
  32.                 string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1'";
  33.                 // 遍历Excel表名
  34.                 OleDbConnection conn = new OleDbConnection(strConn);
  35.                 conn.Open();
  36.                 DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  37.                 conn.Close();
  38.                 foreach (DataRow dr in sheetNames.Rows)
  39.                 {
  40.                     tableList.Add((String)dr["TABLE_NAME"]);
  41.                 }
  42.                 // 读取表中的数据到DataSet
  43.                 DataSet ds = new DataSet();
  44.                 foreach (string tableName in tableList)
  45.                 {
  46.                     OleDbDataAdapter da = new OleDbDataAdapter("select*from[" + tableName + "]", strConn);
  47.                     da.Fill(ds, tableName);
  48.                 }
  49.                 return ds;

  50.             }
  51.             catch (Exception ex)
  52.             {
  53.                 errorMeg = "read Excel file fail" + ex.Message + "!";
  54.                 return null;
  55.             }
  56.         }

  57.     }
  58. }
复制代码


写Excel
  1. SaveFileDialog saveDialog = new SaveFileDialog();
  2.             saveDialog.DefaultExt = "xlsx";
  3.             saveDialog.Filter = "Excel文件*.xlsx|*.xlsx|Excel文件*.xls|.*xls";
  4.             saveDialog.ShowDialog();
  5.             string saveFileName = saveDialog.FileName;
  6.             WriteExcel WExcel = new WriteExcel();
  7.             WExcel.ExportExcel(saveFileName, "32", 2, 4); // 第2行第4列写入32这个数字
  8.             WExcel.ExportExcel(saveFileName, "33", 3, 4); // 第3行第4列写入33这个数字
  9.             WExcel.ExportExcel(saveFileName, "34", 4, 4); // 第4行第4列写入34这个数字
  10.             MessageBox.Show("执行完毕!!!");
复制代码
WExcel.ExportExcel函数如下:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.Office.Interop.Excel;
  7. using System.Windows.Forms;
  8. using System.IO;
  9. using System.Data;

  10. namespace Operate_Excel
  11. {
  12.     public class WriteExcel
  13.     {
  14.         public void ExportExcel(string saveFileName, string data,int RowCount, int ColumnCount)
  15.         {
  16.             if (saveFileName.IndexOf(":") < 0) return; //被点了取消
  17.             Microsoft.Office.Interop.Excel.Application ExcelApp;
  18.             try
  19.             {
  20.                 ExcelApp = new Microsoft.Office.Interop.Excel.Application();
  21.             }
  22.             catch (Exception)
  23.             {
  24.                 MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
  25.                 return;
  26.             }
  27.             finally{            }

  28.             Microsoft.Office.Interop.Excel.Workbooks workbooks = ExcelApp.Workbooks;
  29.             // 创建一个新的EXCEL表格,原本的内容将被清空
  30.             //Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
  31.             // 在指定的EXCEL中写入新的内容
  32.             Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(@saveFileName);
  33.             Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1

  34.             worksheet.Cells[RowCount + 1, ColumnCount + 1] = data;
  35.             worksheet.Columns.EntireColumn.AutoFit();//列宽自适应

  36.             if (saveFileName != "")
  37.             {
  38.                 try
  39.                 {
  40.                     workbook.Saved = true;
  41.                     workbook.SaveCopyAs(saveFileName);
  42.                 }
  43.                 catch (Exception ex)
  44.                 {
  45.                     MessageBox.Show("导出文件时出错,文件可能正被打开!n" + ex.Message);
  46.                 }
  47.             }

  48.             ExcelApp.Quit();
  49.             GC.Collect();//强行销毁
  50.         }
  51.     }
  52. }
复制代码


欢迎大家分享自己的代码!

算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Python|Opencv|MATLAB|Halcom.cn ( 蜀ICP备16027072号 )

GMT+8, 2024-4-24 18:47 , Processed in 0.204621 second(s), 21 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表