需求:现有2个Excel,一个7000,一个20W,7000在20W是完全存在的。现要分离20W的,拆分成19W3和7000。

条件:两个Excel都有“登录名”,然后用“登录名”去关联2个Excel

引用:Aspose.Cells.dll

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();
}
}

C# 读写Excel的一些方法,Aspose.Cells.dll的更多相关文章

  1. C# Aspose.Cells.dll Excel操作总结

    简介 Aspose.Cells是一款功能强大的 Excel 文档处理和转换控件,不依赖 Microsoft Excel 环境,支持所有 Excel 格式类型的操作. 下载 Aspose.Cells.d ...

  2. C# WinForm 导出导入Excel/Doc 完整实例教程[使用Aspose.Cells.dll]

    [csharp] view plain copy 1.添加引用: Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载.关于它的操作我在“Aspose.Cells操作说明 中文版 下载 ...

  3. C# WinForm使用Aspose.Cells.dll 导出导入Excel/Doc 完整实例教程

    1.添加引用: Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载.关于它的操作我在“Aspose.Cells操作说明 中文版 下载 Aspose C# 导出Excel 实例”一文中的 ...

  4. Aspose.Cells.dll引用导入导出Excel

    Aspose.Cells 导入导出EXCEL 文章出处:http://hi.baidu.com/leilongbing/item/c11467e1819e5417595dd8c1 修改样式       ...

  5. python使用xlrd模块读写Excel文件的方法

    本文实例讲述了python使用xlrd模块读写Excel文件的方法.分享给大家供大家参考.具体如下: 一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi ...

  6. C# 利用Aspose.Cells .dll将本地excel文档转化成pdf(完美破解版 无水印 无中文乱码)

    Aspose.Cells .dll下载  http://pan.baidu.com/s/1slRENLF并引用 C#代码 using System; using System.Collections. ...

  7. Aspose.Cells.dll操作execl

    附件:Aspose.Cells.dll 1.创建execl(不需要服务器或者客户端安装office) public void DCExexl(DataTable dt) {  Workbook wb ...

  8. C# 中 NPOI 库读写 Excel 文件的方法【摘】

    原作:淡水网志 NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件.在处理Excel文件上,NPOI 可以同时兼容 xls 和 xlsx.官网提供了一份 Exa ...

  9. 导出excel设置样式(Aspose.Cells)

    Aspose.Cells.Style style = xlBook.Styles[xlBook.Styles.Add()];style1.Pattern = Aspose.Cells.Backgrou ...

随机推荐

  1. foxmail同步QQ邮箱里的所有文件夹

    随着微信消息的轰炸,我决定重拾邮箱.为了方便管理邮箱,我下载并试用了Foxmail和网易邮箱大师,Foxmail不确定用什么语言开发的,可能是C++或者Delphi(早期应该是Delphi,最新的版本 ...

  2. Linux 10字符串命令病毒的处理记录

    刚上线的测试服务器不停的向外发包,且CPU持续100%,远程登录后查看发现有一长度为10的随机字符串进程,kill掉,会重新生成另外长度为10的字符串进程.删除文件也会重复生成,非常痛苦.查阅cron ...

  3. Swift学习笔记(十四)——字符,常量字符串与变量字符串

    在学习Java过程中,字符串碰到过String和StringBuffer,当中前者是不可变的,不能对字符串进行改动:后者是可变的,能够不断改动. 来到Swift中,对字符串的定义变的更加简单. (1) ...

  4. linux下chmod使用

    用法 chmod使用语法 $ chmod [options] mode[,mode] file1 [file2 ...] 使用ls命令的查看文件或目录的属性 $ ls -l file 八进制语法 ch ...

  5. 求标准分sql

    if object_id('tempdb..#tempTable') is not null Begin drop table #tempTable End [校区],[学年],[考试年级],[考试类 ...

  6. Spring MVC报异常:org.springframework.web.util.NestedServletException: Request processing failed

    在使用SpringMVC绑定基本类型(如String,Integer等)参数时,应通过@RequestParam注解指定具体的参数名称,否则,当源代码在非debug模式下编译后,运行时会引发Handl ...

  7. mysql存储引擎的一点学习心得总结

    首先我们应该了解mysql中的一个重要特性--插件式存储引擎,从名字就能够看出在mysql中,用户能够依据自己的需求随意的选择存储引擎.实际上也是这样.即使在同一个数据库中.不同的表也能够使用不同的存 ...

  8. google全球地址

    IP Addresses of Google Global Cache www.kookle.co.nr Bulgaria 93.123.23.1 93.123.23.2 93.123.23.3 93 ...

  9. 茗洋Easy UI 1.3.5 部分问题解决系列专题[自定义alert关闭时间,自动关]

    [评论,楼层数为30的倍数的,我送你我自己的博客园的皮肤,该博客参与活动] 这次我又给大家带来的EasyUI的我研究拓展的新特性 我使用的是  EasyUI 1.3.5版本的,项目是ASP.NET M ...

  10. 关于tcp中time_wait状态的4个问题

    time_wait是个常问的问题.tcp网络编程中最不easy理解的也是它的time_wait状态,这也说明了tcp/ip四次挥手中time_wait状态的重要性. 以下通过4个问题来描写叙述它 问题 ...