读写Excel
需求:现有2个Excel,一个7000,一个20W,7000在20W是完全存在的。现要分离20W的,拆分成19W3和7000。
条件:两个Excel都有“登录名”,然后用“登录名”去关联2个Excel
public void Excel()
{
//获取第一个Excel,20W
string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/测试20W.xlsx";
System.Data.DataTable table = GetTableFromExcel("sheet1", filePath); //克隆
System.Data.DataTable table20W_new = table.Clone();
System.Data.DataTable table7000_new = table.Clone(); //获取第二个Excel,7000
string filePath_7000 = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/测试7000.xls";
System.Data.DataTable table_7000 = GetTableFromExcel("sheet1", filePath_7000); //循环20W人中的挑出来
for (int i = ; i < table.Rows.Count; ++i)
{
//20W
DataRow dateRow = table.Rows[i];
string login_name = dateRow["登录名"].ToString(); //
DataRow[] drss = table_7000.Select("登录名 = '" + login_name + "'");
if (drss.Length > )
{
table7000_new.ImportRow(dateRow);
}
else
{
table20W_new.ImportRow(dateRow);
}
}
//导出Excel
DataTableExport(table7000_new, AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/7000.xlsx");
DataTableExport(table20W_new, AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "daochu/22W.xlsx");
}
获取Excel内容,转成DataTable。
/// <summary>
/// 获取Excel内容。
/// </summary>
/// <param name="sheetName">工作表名称,例:sheet1</param>
/// <param name="filePath">Excel路径</param>
/// <returns></returns>
private DataTable GetTableFromExcel(string sheetName, string filePath)
{
const string connStrTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;\"";
DataTable dt = null;
if (!System.IO.File.Exists(filePath))
{
// don't find file
return null;
}
OleDbConnection conn = new OleDbConnection(string.Format(connStrTemplate, filePath));
try
{
conn.Open();
if (sheetName == null || sheetName.Trim().Length == )
{
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = schemaTable.Rows[]["TABLE_NAME"].ToString().Trim();
}
else
{
sheetName += "$";
} string strSQL = "Select * From [" + sheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSQL, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dt = ds.Tables[];
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
} return dt;
}
将DataTable的数据写进Excel里(用的Aspose.Cells.dll)
/// <summary>
/// DataTable数据导出Excel
/// </summary>
/// <param name="data"></param>
/// <param name="filepath"></param>
public static void DataTableExport(DataTable data, string filepath)
{
try
{
Workbook book = new Workbook(); //创建工作簿
Worksheet sheet = book.Worksheets[0]; //创建工作表
Cells cells = sheet.Cells; //单元格
//创建样式
Aspose.Cells.Style style = book.Styles[book.Styles.Add()];
style.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 左边界线
style.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 右边界线
style.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 上边界线
style.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //应用边界线 下边界线
style.HorizontalAlignment = TextAlignmentType.Center; //单元格内容的水平对齐方式文字居中
style.Font.Name = "宋体"; //字体
//style1.Font.IsBold = true; //设置粗体
style.Font.Size = 11; //设置字体大小
//style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0); //背景色
//style.Pattern = Aspose.Cells.BackgroundType.Solid; int Colnum = data.Columns.Count;//表格列数
int Rownum = data.Rows.Count;//表格行数
//生成行 列名行
for (int i = 0; i < Colnum; i++)
{
cells[0, i].PutValue(data.Columns[i].ColumnName); //添加表头
cells[0, i].SetStyle(style); //添加样式
}
//生成数据行
for (int i = 0; i < Rownum; i++)
{
for (int k = 0; k < Colnum; k++)
{
cells[1 + i, k].PutValue(data.Rows[i][k].ToString()); //添加数据
cells[1 + i, k].SetStyle(style); //添加样式
}
}
sheet.AutoFitColumns(); //自适应宽
book.Save(filepath); //保存
GC.Collect();
}
catch (Exception e)
{
logger.Error("生成excel出错:" + e.Message);
}
}
将List的数据写进Excel里(用的Aspose.Cells.dll)
/// <summary>
/// 导出excel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">Ilist集合</param>
/// <param name="filepath">保存的地址</param>
public static void Export<T>(IList<T> data, string filepath)
{
try
{
Workbook workbook = new Workbook();
Worksheet sheet = (Worksheet)workbook.Worksheets[]; PropertyInfo[] ps = typeof(T).GetProperties();
var colIndex = "A";
foreach (var p in ps)
{
// sheet.Cells[colIndex + 1].PutValue(p.Name);//设置表头名称 要求表头为中文所以不用 p.name 为字段名称 可在list第一条数据为表头名称
int i = ;
foreach (var d in data)
{
sheet.Cells[colIndex + i].PutValue(p.GetValue(d, null));
i++;
}
colIndex = getxls_top(colIndex); //((char)(colIndex[0] + 1)).ToString();//表头 A1/A2/
}
//workbook.Shared = true;
workbook.Save(filepath);
GC.Collect();
}
catch (Exception e)
{
logger.Error("生成excel出错:" + e.Message);
}
}
/// <summary>
/// 生成新的对应的列 A-Z AA-ZZ
/// </summary>
/// <param name="top">当前列</param>
/// <returns></returns>
private static string getxls_top(string top)
{
char[] toplist = top.ToArray();
var itemtop = top.Last();
string topstr = string.Empty;
if ((char)itemtop == )//最后一个是Z
{
if (toplist.Count() == )
{
topstr = "AA";
}
else
{
toplist[] = (char)(toplist[] + );
toplist[toplist.Count() - ] = 'A';
foreach (var item in toplist)
{
topstr += item.ToString();
}
}
}
else//最后一个不是Z 包括top为两个字符
{
itemtop = (char)(itemtop + );
toplist[toplist.Count() - ] = itemtop; foreach (var item in toplist)
{
topstr += item.ToString();
}
}
return topstr;
}
将DataTable的数据写进Excel里(用的Microsoft.Office.Interop.Excel.dll)
此方法在大量数据的时候很慢,例如22W条数据,建议使用Aspose.Cells.dll,速度快很多
/// <summary>
/// 将DataTable的数据写进Excel里
/// </summary>
/// <param name="tmpDataTable">DataTable数据</param>
/// <param name="strFileName">Excel路径</param>
public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
if (tmpDataTable == null)
{
return;
}
int rowNum = tmpDataTable.Rows.Count;
int columnNum = tmpDataTable.Columns.Count;
int rowIndex = ;
int columnIndex = ; //需要引用Microsoft.Office.Interop.Excel.dll
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = ;
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); //将DataTable的列名导入Excel表第一行
foreach (DataColumn dc in tmpDataTable.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
} //将DataTable中的数据导入Excel中
for (int i = ; i < rowNum; i++)
{
rowIndex++;
columnIndex = ;
for (int j = ; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
}
}
//xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));
xlBook.SaveCopyAs(strFileName);
}
原生的DataTable生成Excel(无需引用第三方dll)
/// <summary>
/// 将DataTable的数据写进Excel里
/// </summary>
/// <param name="tdKeChengZhuanJiaTongJi">DataTable</param>
/// <param name="sheet">sheet自定义名称</param>
/// <param name="fileName">Excel路径</param>
public static void DataTabletoExcel(DataTable dt, string sheet, string fileName)
{
String sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0 Xml;\"";
//string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;'";
//String sConnectionString = "Provider=Microsoft.ACE.OLEDB.14.0;Data Source=" + fileName + ";Extended Properties=\"Excel 14.0 Xml;\"";
//String sConnectionString = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + fileName + ";Extended Properties=\"Excel 16.0 Xml;HDR=YES;\""; OleDbConnection cn = new OleDbConnection(sConnectionString); int rowNum = dt.Rows.Count;//获取行数
int colNum = dt.Columns.Count;//获取列数
string sqlText = "";//带类型的列名
string sqlValues = "";//值
string colCaption = "";//列名
for (int i = ; i < colNum; i++)
{
if (i != )
{
sqlText += " , ";
colCaption += " , ";
}
sqlText += "[" + dt.Columns[i].Caption.ToString() + "] VarChar";//生成带VarChar列的标题
colCaption += "[" + dt.Columns[i].Caption.ToString() + "]";//生成列的标题
}
try
{
//打开连接
cn.Open();
string sqlCreate = "CREATE TABLE [" + sheet.ToString() + "] (" + sqlText + ")";
OleDbCommand cmd = new OleDbCommand(sqlCreate, cn);
//创建Excel文件
cmd.ExecuteNonQuery();
for (int srow = ; srow < rowNum; srow++)
{
sqlValues = "";
for (int col = ; col < colNum; col++)
{
if (col != )
{
sqlValues += " , ";
}
sqlValues += "'" + dt.Rows[srow][col].ToString() + "'";//拼接Value语句
}
String queryString = "INSERT INTO [" + sheet.ToString() + "] (" + colCaption + ") VALUES (" + sqlValues + ")";
cmd.CommandText = queryString;
cmd.ExecuteNonQuery();//插入数据
}
}
catch
{
//生成日志
}
finally
{
cn.Close();
}
}
读写Excel的更多相关文章
- MFC vs2012 Office2013 读写excel文件
		近期在忙一个小项目(和同学一起搞的),在这里客户要求不但读写txt,而且可以读写excel文件,这里本以为很简单,结果...废话少说,过程如下: 笔者环境:win7 64+VS2012+Office2 ... 
- C# 使用 NPOI 库读写 Excel 文件(转载)
		NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼 容xls 和 xlsx.官网提供了一份Examples,给出了 ... 
- Python3.4如何读写Excel
		在python3.x(散仙使用的版本是python3.4)里,我们应该如何操作excel. 首先在python3.4里,我们可以使用新的python类库,来支持3.x之后的读写excel 针对 03版 ... 
- 用Python读写Excel文件(转)
		原文:google.com/ncr 虽然天天跟数据打交道,也频繁地使用Excel进行一些简单的数据处理和展示,但长期以来总是小心地避免用Python直接读写Excel文件.通常我都是把数据保存为以TA ... 
- 使用NPOI读写Excel、Word
		NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ... 
- 【原创】.NET读写Excel工具Spire.Xls使用(1)入门介绍
		在.NET平台,操作Excel文件是一个非常常用的需求,目前比较常规的方法有以下几种: 1.Office Com组件的方式:这个方式非常累人,微软的东西总是这么的复杂,使用起来可能非常不便,需要安装E ... 
- 【原创】.NET读写Excel工具Spire.Xls使用(2)Excel文件的控制
		本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html .NET读写Excel工具Spire.Xls使用文章 ... 
- 【原创】.NET读写Excel工具Spire.Xls使用(3)单元格控制
		本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html .NET读写Excel工具Spire.Xls使用文章 ... 
- 【原创】.NET读写Excel工具Spire.Xls使用(4)对数据操作与控制
		本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html .NET读写Excel工具Spire.Xls使用文章 ... 
- 【原创】.NET读写Excel工具Spire.Xls使用(5)重量级的Excel图表功能
		本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html .NET读写Excel工具Spire.Xls使用文章 ... 
随机推荐
- sql server 发布时提示'dbo.sysmergepublications'无效的解决办法
			对数据库进行数据库复制.订阅时经常会出现各种奇怪的问题 如果你对数据库进行多次发布.删除发布操作时可能会提示“dbo.sysmergepublications”无效的问题, 可以使用以下方法解决: U ... 
- Lowest Common Ancestor in Binary Tree
			The problem: Given node P and node Q in a binary tree T. Find out the lowest common ancestor of the ... 
- (转载)PHP strtotime函数详解
			(转载)http://www.jb51.net/article/21495.htm strtotime函数是一个很好的函数,灵活的运用它,会给你的工作带来不少方便.但PHP的手册中却对此函数的参数没作 ... 
- 数据结构(线段树):BZOJ 1018: [SHOI2008]堵塞的交通traffic
			1018: [SHOI2008]堵塞的交通traffic Time Limit: 3 Sec Memory Limit: 162 MBSubmit: 2638 Solved: 864 Descri ... 
- C#:ref和out的联系及区别
			一:ref 关键字使参数按引用传递. 其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中.若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字. ... 
- arcgis数据文件使用
			dem数据打开,保存,使用 打开 
- 高效算法——B 抄书  copying books,uva714
			Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %llu Submit Status Description ... 
- WEB性能测试:你应该带上VisualStudio2010
			原文地址:http://www.16aspx.com/Article/62 在Web性能测试方面,增加了循环(Loops)和条件(Conditions),让开发人员可以为他们的应用程序写出更复杂,更智 ... 
- 广度优先搜索BFS
			广度优先搜索可以形成一个广度优先搜索树 算法时间为O(V+E),两重循环 输入:图g,起点start(int) 需要的数据结构:队列Q.color数组(存放每个顶点的颜色) 算法过程: 1. 预处理: ... 
- [Locked] Paint House I & II
			Paint House There are a row of n houses, each house can be painted with one of the three colors: red ... 
