下面的这几个方法是我在项目中经常用到的,欢迎大家批评指正

读取Excel表中的数据

第一种:功能丰富,速度慢

     /// <summary>
/// 从Excel读取数据
/// </summary>
/// <param name="path">Excel文档的全路径</param>
/// <returns>将一行作为一个对象,所以返回的是很多行数据的对象</returns>
public Model[] ReadDataFromExcel(string path)
{
List<Model> list = new List<Model>();
Application excelApp = null;
try
{
excelApp = new Application() { Visible = false, DefaultFilePath = "", DisplayAlerts = true, SheetsInNewWorkbook = };
Workbooks books = excelApp.Workbooks;
if (File.Exists(path))
{
Workbook book = books.Open(path);
Worksheet sheet = book.Sheets.get_Item();
if (sheet != null)
{
int rowNum = sheet.UsedRange.Rows.Count;
DateTime timeLimit;
timeLimit = GetTime(((Range)sheet.Cells[, "B"]).Text.ToString()).AddSeconds(sectionNum*timeSpan*); //从第2行开始读数据
for (int i = ; i < rowNum; i++)
{
if (((Range)sheet.Cells[i, "A"]).Text != "" && ((Range)sheet.Cells[i, "B"]).Text != "")
{ if (timeLimit.CompareTo(GetTime(((Range)sheet.Cells[i, "B"]).Text.ToString())) < )
{
break;
}
else
{
Model m = new Model()
{
SN = ((Range)sheet.Cells[i, "A"]).Text.ToString(),
time = GetTime(((Range)sheet.Cells[i, "B"]).Text.ToString()),
ch1 = ((Range)sheet.Cells[i, "C"]).Text.ToString(),
ch2 = ((Range)sheet.Cells[i, "D"]).Text.ToString(),
ch3 = ((Range)sheet.Cells[i, "E"]).Text.ToString(),
ch4 = ((Range)sheet.Cells[i, "F"]).Text.ToString()
};
list.Add(m);
} }
} }
} }
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
//执行完读取Excel数据后,将关闭该进程
KillExcel(excelApp);
}
return list.ToArray();
}

第二种:速度快

  public DataTable ExcelToDS(string filePath)
{
string connStr = "";
string fileType = System.IO.Path.GetExtension(Path.GetFileName(filePath));
if (string.IsNullOrEmpty(fileType))
{
return null;
}
if (fileType == ".xls")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, connStr);
ds = new DataSet();
myCommand.Fill(ds, "table1");
return ds.Tables[];
}

关闭Excel进程:

  [DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hwnd, out int processId);
public void KillExcel(Application excelApp)
{
try
{
if(excelApp!=null)
{
int processId;
GetWindowThreadProcessId(new IntPtr(excelApp.Hwnd), out processId);
Process p = Process.GetProcessById(processId);
p.Kill();
}
}
catch (Exception ex)
{
throw ex;
}
}

读取Excel单元格数据:

  /// <summary>
/// 获取单元格数据
/// </summary>
/// <param name="sheet"></param>
/// <param name="row"></param>
/// <param name="col"></param>
/// <returns></returns>
public string GetValue(Worksheet sheet, int row, int col)
{
// 取得单元格.
var cell = (Range)sheet.Cells[row, col];
if ((bool)cell.MergeCells == true)
{
// 本单元格是 “合并单元格”
if (cell.MergeArea.Row == row
&& cell.MergeArea.Column == col)
{
// 当前单元格 就是 合并单元格的 左上角 内容.
return cell.Text.ToString();
}
else
{
// 返回 合并单元格的 左上角 内容.
return ((Range)(sheet.Cells[cell.MergeArea.Row, cell.MergeArea.Column])).Text.ToString();
}
}
else
{
// 本单元格是 “普通单元格”
// 获取文本信息.
return cell.Text.ToString();
}
}

根据文本获取该文本所在行号和所占的行数,一般主要用来读取合并单元格

/// <summary>
/// 根据文本获取行号和所占行数
/// </summary>
/// <param name="sheet">查询的表单</param>
/// <param name="text">查询的文本</param>
/// <param name="rowNumber">行号</param>
/// <param name="rowCounts">所占行数</param>
public void GetRowNumber(Worksheet sheet, string text,out int rowNumber,out int rowCounts)
{
rowNumber = -;
rowCounts = -;
foreach(Range range in sheet.UsedRange)
{
if (range.Value == null)
continue;
if (range.Value.ToString() == text)
{
rowNumber = range.Row;
if ((bool)range.MergeCells == true)
rowCounts = range.MergeArea.Rows.Count;
else
rowCounts = ;
break;
}
}
}

C#之Excel操作的更多相关文章

  1. Npoi导入导出Excel操作

    之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...

  2. Delphi Excel 操作大全

    Delphi Excel 操作大全 (一) 使用动态创建的方法首先创建 Excel 对象,使用ComObj:var ExcelApp: Variant;ExcelApp := CreateOleObj ...

  3. C#EXCEL 操作类--C#ExcelHelper操作类

    主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Excel文件5.将指定的集合数据导出至Exce ...

  4. Excel 操作类

    转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...

  5. C# excel操作

    开源的Excel操作项目: http://www.cnblogs.com/lwme/archive/2011/11/27/2265323.html 添加引用:Microsoft Excel 11.0 ...

  6. [Excel操作]Microsoft Office Excel 不能访问文件

    最近,客户服务器迁移,因操作系统环境变化而引起的的环境问题一堆,遇到的问题并解决方法在“[Excel]操作”类别会体现. Microsoft Office Excel 不能访问文件“C:\\LMSEx ...

  7. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  8. 报表中的Excel操作之Aspose.Cells(Excel模板)

    原文:报表中的Excel操作之Aspose.Cells(Excel模板) 本篇中将简单记录下Aspose.Cells这个强大的Excel操作组件.这个组件的强大之处,就不多说,对于我们的报表总是会有导 ...

  9. C# Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  10. Excel操作 Microsoft.Office.Interop.Excel.dll的使用

    ----转载: http://www.cnblogs.com/lanjun/archive/2012/06/17/2552920.html 先说说题外话,前段时间近一个月,我一直在做单据导入功能,其中 ...

随机推荐

  1. mysql新手入门随笔2

    17.创建表 CREATE TABLE tbname(columnname1 类型 约束条件, columnname2 类型 约束条件,-); 三大类型:数值型,时间日期型,字符串类型 六大约束条件: ...

  2. [poj3252]Round Numbers_数位dp

    Round Numbers poj3252 题目大意:求一段区间内Round Numbers的个数. 注释:如果一个数的二进制表示中0的个数不少于1的个数,我们就说这个数是Round Number.给 ...

  3. h5移动端屏幕适配

    1.rem <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

  4. php项目中常用的log日志记录方法

    function log_result($str) { if (LOG_WRITEOUT == 1) { $fp = fopen ( "log.txt", "a+&quo ...

  5. bisect 二分查找

    先说明的是,使用这个模块的函数前先确保操作的列表是已排序的. 先看看 insort  函数: 其插入的结果是不会影响原有的排序. 再看看 bisect  函数: 其目的在于查找该数值将会插入的位置并返 ...

  6. Android Notification setLatestEventInfo方法已废弃

    代替setLatestEventInfo的方法是用Notification.Builder创建Builder对象,通过该对象设置Notification相关属性. otification.Builde ...

  7. 01-JavaScript之变量

    这个系列的文章主要讲解JavaScript的常见用法,适合于初中级的前端开发人员,也可以对比TypeScript的系列文章来看. 先介绍JavaScript的变量与常见变量的函数,代码如下: //变量 ...

  8. 根据HTML5的新方法 drag & drop 方法实现表格拖拽实例

    上一次学习了html5的drag和drop方法,传送门  就自己写了个例子加深自己对drag和drop的理解.不过一开始不是很简单,遇到了不少问题.还好网络万能的,什么都能查到,总算完成了. 说明和详 ...

  9. 关于网页设计的css+html相对定位和决定定位的理解

    css中有很多定位,其中最重要的是相对定位和绝对定位: 定位很重要,不搞好,网页就会很乱,显示的完全不是自己想要的效果,自己必须掌握: 首先说一个重要的结论:绝对定位,是不占位置的,总是相对离自己最近 ...

  10. ASP.NET 访问项目网站以外的目录文件

    简单的说,可以通过在 IIS 添加虚拟目录的方法做到,获取访问路径的时候就用 HttpContext.Current.Server.MapPath("~/xxx"); 的方式. 下 ...