C# 读取Excel方法
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
namespace 怡心爬虫工具
{
public class ExcelOptions
{
private Stopwatch wath = new Stopwatch();
/// <summary>
/// 使用COM读取Excel
/// </summary>
/// <param name="excelFilePath">路径</param>
/// <returns>DataTabel</returns>
public System.Data.DataTable GetExcelData(string excelFilePath)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Sheets sheets;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
object oMissiong = System.Reflection.Missing.Value;
System.Data.DataTable dt = new System.Data.DataTable();
wath.Start();
try
{
if (app == null)
{
return null;
}
workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
//将数据读入到DataTable中——Start
sheets = workbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);//读取第一张表
if (worksheet == null)
return null;
string cellContent;
int iRowCount = worksheet.UsedRange.Rows.Count;
int iColCount = worksheet.UsedRange.Columns.Count;
Microsoft.Office.Interop.Excel.Range range;
//负责列头Start
DataColumn dc;
int ColumnID = 1;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, 1];
while (range.Text.ToString().Trim() != "")
{
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = range.Text.ToString().Trim();
dt.Columns.Add(dc);
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, ++ColumnID];
}
//End
for (int iRow = 2; iRow <= iRowCount; iRow++)
{
DataRow dr = dt.NewRow();
for (int iCol = 1; iCol <= iColCount; iCol++)
{
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCol];
cellContent = (range.Value2 == null) ? "" : range.Text.ToString();
//if (iRow == 1)
//{
// dt.Columns.Add(cellContent);
//}
//else
//{
dr[iCol - 1] = cellContent;
//}
}
//if (iRow != 1)
dt.Rows.Add(dr);
}
wath.Stop();
TimeSpan ts = wath.Elapsed;
//将数据读入到DataTable中——End
return dt;
}
catch
{
return null;
}
finally
{
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
/// <summary>
/// 使用COM,多线程读取Excel(1 主线程、4 副线程)
/// </summary>
/// <param name="excelFilePath">路径</param>
/// <returns>DataTabel</returns>
public System.Data.DataTable ThreadReadExcel(string excelFilePath)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Sheets sheets = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
object oMissiong = System.Reflection.Missing.Value;
System.Data.DataTable dt = new System.Data.DataTable();
wath.Start();
try
{
if (app == null)
{
return null;
}
workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
//将数据读入到DataTable中——Start
sheets = workbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);//读取第一张表
if (worksheet == null)
return null;
string cellContent;
int iRowCount = worksheet.UsedRange.Rows.Count;
int iColCount = worksheet.UsedRange.Columns.Count;
Microsoft.Office.Interop.Excel.Range range;
//负责列头Start
DataColumn dc;
int ColumnID = 1;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, 1];
//while (range.Text.ToString().Trim() != "")
while (iColCount >= ColumnID)
{
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
string strNewColumnName = range.Text.ToString().Trim();
if (strNewColumnName.Length == 0) strNewColumnName = "_1";
//判断列名是否重复
for (int i = 1; i < ColumnID; i++)
{
if (dt.Columns[i - 1].ColumnName == strNewColumnName)
strNewColumnName = strNewColumnName + "_1";
}
dc.ColumnName = strNewColumnName;
dt.Columns.Add(dc);
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, ++ColumnID];
}
//End
//数据大于500条,使用多进程进行读取数据
if (iRowCount - 1 > 500)
{
//开始多线程读取数据
//新建线程
int b2 = (iRowCount - 1) / 10;
DataTable dt1 = new DataTable("dt1");
dt1 = dt.Clone();
SheetOptions sheet1thread = new SheetOptions(worksheet, iColCount, 2, b2 + 1, dt1);
Thread othread1 = new Thread(new ThreadStart(sheet1thread.SheetToDataTable));
othread1.Start();
//阻塞 1 毫秒,保证第一个读取 dt1
Thread.Sleep(1);
DataTable dt2 = new DataTable("dt2");
dt2 = dt.Clone();
SheetOptions sheet2thread = new SheetOptions(worksheet, iColCount, b2 + 2, b2 * 2 + 1, dt2);
Thread othread2 = new Thread(new ThreadStart(sheet2thread.SheetToDataTable));
othread2.Start();
DataTable dt3 = new DataTable("dt3");
dt3 = dt.Clone();
SheetOptions sheet3thread = new SheetOptions(worksheet, iColCount, b2 * 2 + 2, b2 * 3 + 1, dt3);
Thread othread3 = new Thread(new ThreadStart(sheet3thread.SheetToDataTable));
othread3.Start();
DataTable dt4 = new DataTable("dt4");
dt4 = dt.Clone();
SheetOptions sheet4thread = new SheetOptions(worksheet, iColCount, b2 * 3 + 2, b2 * 4 + 1, dt4);
Thread othread4 = new Thread(new ThreadStart(sheet4thread.SheetToDataTable));
othread4.Start();
//主线程读取剩余数据
for (int iRow = b2 * 4 + 2; iRow <= iRowCount; iRow++)
{
DataRow dr = dt.NewRow();
for (int iCol = 1; iCol <= iColCount; iCol++)
{
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCol];
cellContent = (range.Value2 == null) ? "" : range.Text.ToString();
dr[iCol - 1] = cellContent;
}
dt.Rows.Add(dr);
}
othread1.Join();
othread2.Join();
othread3.Join();
othread4.Join();
//将多个线程读取出来的数据追加至 dt1 后面
foreach (DataRow dr in dt.Rows)
dt1.Rows.Add(dr.ItemArray);
dt.Clear();
dt.Dispose();
foreach (DataRow dr in dt2.Rows)
dt1.Rows.Add(dr.ItemArray);
dt2.Clear();
dt2.Dispose();
foreach (DataRow dr in dt3.Rows)
dt1.Rows.Add(dr.ItemArray);
dt3.Clear();
dt3.Dispose();
foreach (DataRow dr in dt4.Rows)
dt1.Rows.Add(dr.ItemArray);
dt4.Clear();
dt4.Dispose();
return dt1;
}
else
{
for (int iRow = 2; iRow <= iRowCount; iRow++)
{
DataRow dr = dt.NewRow();
for (int iCol = 1; iCol <= iColCount; iCol++)
{
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCol];
cellContent = (range.Value2 == null) ? "" : range.Text.ToString();
dr[iCol - 1] = cellContent;
}
dt.Rows.Add(dr);
}
}
wath.Stop();
TimeSpan ts = wath.Elapsed;
//将数据读入到DataTable中——End
return dt;
}
catch
{
return null;
}
finally
{
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
workbook = null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
/*
object objmissing = System.Reflection.Missing.Value;
Excel.ApplicationClass application = new ApplicationClass();
Excel.Workbook book = application.Workbooks.Add(objmissing);
Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets.Add(objmissing,objmissing,objmissing,objmissing);
//操作过程 ^&%&×&……&%&&……
//释放
sheet.SaveAs(path,objmissing,objmissing,objmissing,objmissing,objmissing,objmissing,objmissing,objmissing);
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)book);
application.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)application);
System.GC.Collect();
*/
}
}
/// <summary>
/// 删除Excel行
/// </summary>
/// <param name="excelFilePath">Excel路径</param>
/// <param name="rowStart">开始行</param>
/// <param name="rowEnd">结束行</param>
/// <param name="designationRow">指定行</param>
/// <returns></returns>
public string DeleteRows(string excelFilePath, int rowStart, int rowEnd, int designationRow)
{
string result = "";
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Sheets sheets;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
object oMissiong = System.Reflection.Missing.Value;
try
{
if (app == null)
{
return "分段读取Excel失败";
}
workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
sheets = workbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);//读取第一张表
if (worksheet == null)
return result;
Microsoft.Office.Interop.Excel.Range range;
//先删除指定行,一般为列描述
if (designationRow != -1)
{
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Rows[designationRow, oMissiong];
range.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftUp);
}
Stopwatch sw = new Stopwatch();
sw.Start();
int i = rowStart;
for (int iRow = rowStart; iRow <= rowEnd; iRow++, i++)
{
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Rows[rowStart, oMissiong];
range.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftUp);
}
sw.Stop();
TimeSpan ts = sw.Elapsed;
workbook.Save();
//将数据读入到DataTable中——End
return result;
}
catch
{
return "分段读取Excel失败";
}
finally
{
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
public void ToExcelSheet(DataSet ds, string fileName)
{
Microsoft.Office.Interop.Excel.Application appExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbookData = null;
Microsoft.Office.Interop.Excel.Worksheet worksheetData;
Microsoft.Office.Interop.Excel.Range range;
try
{
workbookData = appExcel.Workbooks.Add(System.Reflection.Missing.Value);
appExcel.DisplayAlerts = false;//不显示警告
//xlApp.Visible = true;//excel是否可见
//
//for (int i = workbookData.Worksheets.Count; i > 0; i--)
//{
// Microsoft.Office.Interop.Excel.Worksheet oWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbookData.Worksheets.get_Item(i);
// oWorksheet.Select();
// oWorksheet.Delete();
//}
for (int k = 0; k < ds.Tables.Count; k++)
{
worksheetData = (Microsoft.Office.Interop.Excel.Worksheet)workbookData.Worksheets.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
// testnum--;
if (ds.Tables[k] != null)
{
worksheetData.Name = ds.Tables[k].TableName;
//写入标题
for (int i = 0; i < ds.Tables[k].Columns.Count; i++)
{
worksheetData.Cells[1, i + 1] = ds.Tables[k].Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheetData.Cells[1, i + 1];
//range.Interior.ColorIndex = 15;
range.Font.Bold = true;
range.NumberFormatLocal = "@";//文本格式
range.EntireColumn.AutoFit();//自动调整列宽
// range.WrapText = true; //文本自动换行
range.ColumnWidth = 15;
}
//写入数值
for (int r = 0; r < ds.Tables[k].Rows.Count; r++)
{
for (int i = 0; i < ds.Tables[k].Columns.Count; i++)
{
worksheetData.Cells[r + 2, i + 1] = ds.Tables[k].Rows[r][i];
//Range myrange = worksheetData.get_Range(worksheetData.Cells[r + 2, i + 1], worksheetData.Cells[r + 3, i + 2]);
//myrange.NumberFormatLocal = "@";//文本格式
myrange.EntireColumn.AutoFit();//自动调整列宽
myrange.WrapText = true; //文本自动换行
//myrange.ColumnWidth = 15;
}
// rowRead++;
//System.Windows.Forms.Application.DoEvents();
}
}
worksheetData.Columns.EntireColumn.AutoFit();
workbookData.Saved = true;
}
}
catch (Exception ex) { }
finally
{
workbookData.SaveCopyAs(fileName);
workbookData.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
appExcel.Quit();
GC.Collect();
}
}
}
class SheetOptions
{
Microsoft.Office.Interop.Excel.Worksheet worksheet;
int iColCount;
int star;
int end;
System.Data.DataTable dt;
public SheetOptions(Microsoft.Office.Interop.Excel.Worksheet worksheet, int iColCount, int star, int end, System.Data.DataTable dt)
{
this.worksheet = worksheet;
this.iColCount = iColCount;
this.star = star;
this.end = end;
this.dt = dt;
}
public void SheetToDataTable()
{
string cellContent;
Microsoft.Office.Interop.Excel.Range range;
for (int iRow = star; iRow <= end; iRow++)
{
System.Data.DataRow dr = dt.NewRow();
for (int iCol = 1; iCol <= iColCount; iCol++)
{
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCol];
cellContent = (range.Value2 == null) ? "" : range.Text.ToString();
dr[iCol - 1] = cellContent;
}
dt.Rows.Add(dr);
}
}
}
}
C# 读取Excel方法相关推荐
- python3读取excel方法封装_Python读取Excel的方法封装
今天需要从一个Excel文档(.xls)中导数据到数据库的某表,开始是手工一行行输的.后来想不能一直这样,就用Python写了下面的代码,可以很方便应对这种场景.比如利用我封装的这些方法可以很方便地生 ...
- JAVA 的读取Excel方法_纯Java的方式读取excel2007
* 首先介绍excel2007文件的格式,这里单只工作表文件,不包括加载宏的以及其他格式的,即.xlsx扩展名的 * 你可以把Book1.xlsx这个文件用解压缩文件打开,这是office2007的新 ...
- python3读取excel方法封装_python-excel读写封装
import os from openpyxl import load_workbook import logging from utils import project_path class DoE ...
- python爬网页数据到 excel 自动化_Selenium2+python自动化之读取Excel数据(xlrd)
前言 当登录的账号有多个的时候,我们一般用excel存放测试数据,本节课介绍,python读取excel方法,并保存为字典格式. 一.环境准备 1.先安装xlrd模块,打开cmd,输入pip inst ...
- python读取表格数据_Python读取Excel数据并根据列名取值
一直想将自己接触到的东西梳理一遍,可就是迈不出第一步,希望从这篇总结开始不要再做行动的矮人了. 最近测试过程中需要用到python读取excel用例数据,于是去了解和学习了下xlrd库,这里只记录使用 ...
- Java读取Excel文件
首先下载jxl.jar包,下载地址:http://download.csdn.net/detail/prstaxy/4469935 然后在工程文件上右键选Built Path-Configure Bu ...
- python接口自动化(三十七)-封装与调用--读取excel 数据(详解)
简介 在进行软件接口测试或设计自动化测试框架时,一个不比可避免的过程就是: 参数化,在利用python进行自动化测试开发时,通常会使用excel来做数据管理,利用xlrd.xlwt开源包来读写exce ...
- Easyexcel·读取excel
Easyexcel·读取excel 依赖 数据表 表的实体类 接口 表的crud操作 此接口用于将excel数据写入mysql测试表表中 测试数据导写入到excle中与读取excel数据 读取exce ...
- NPOI操作Excel 002:读取Excel
本文讲述如何通过NPOI来读取Excel. 需要准备的dll见: http://blog.csdn.net/yysyangyangyangshan/article/details/42614181 环 ...
最新文章
- ​赠书 | 云游戏搭上 5G 快车,华为、腾讯争相布局
- python批量图片转pdf,用python 制作图片转pdf工具
- gui 设计的简单计算器 java,编写Java GUI程序,实现一个简单计算器。要求如下: (1)......
- 人人皆知Python功能,你还不了解嘛?
- php 生产环境调错
- Raki的读paper小记:WaveTransformer: A Novel Architecture for Audio Captioning
- 一篇好文之Android文本软键盘全解
- 如何在Keil中的添加和使用STC芯片型号
- Python functools模块之cmp_to_key
- 使用Java实现经典的进程同步问题--哲学家进餐问题
- windows 10 连接android手机助手,Win10手机助手怎么用?win10手机助手使用方法
- HBuilder打包
- pdf和word等文档添加水印
- 概率论应用题,模型汇总(排去抽球模型)
- Android 7.0下拍照和裁剪图片
- 运放指标-压摆率SR
- Unity开发VR项目——问题集锦
- the Graph子图部署(使用Hosted Service)
- 【电泳仪品牌】生科必知的电泳仪品牌
- EasyPoi 实现Word文档内容替换3种情况(正常文本替换、表格文本替换、图表替换)
热门文章
- 陕西省2019年初中计算机试题,陕西省2019年英语中考试题及答案解析(Word版).pdf
- TOA定位算法的关系与泰勒级数法的原理
- 广平县北方计算机第一届PS设计大赛
- JPA踩坑笔记(二)- 分页
- Linux检查4k对齐,linux查看硬盘4K对齐方法
- linux gtx驱动程序,linux GTX1080TI安装显卡驱动小记
- tplink怎么进去_TP-link无线路由器设置图文教程
- 几年前我们都喜欢用的日本手机, 为什么如今中国人就是不买账呢?
- CPU 与 内存之间的三级缓存的实现原理
- 【MySQL基本学习】