1 winform 读取excel文档

1)点击button按钮,弹出上传excel窗口

private  void button_headcompany_Click(object sender, EventArgs e)
{
string HeadCompany_rowValue = HeadCompany_row.Text;
string HeadCompany_columnValue = HeadCompany_column.Text;
if (string.IsNullOrEmpty(HeadCompany_rowValue) || string.IsNullOrEmpty(HeadCompany_columnValue))
{
MessageBox.Show("请填写行和列的值,例如 行A5 列BB", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
ButtonClick("总公司汇总", HeadCompany_rowValue, HeadCompany_columnValue);
}

  

2)判断是否上传的文档格式是否正常 xls和xlsx类型的文档

 public static void ButtonClick(string SheetType,string rowValue,string ColumnValue)
{
string worksheetname = string.Empty;
string filepath = "";
//导入本地文件
OpenFileDialog file = new OpenFileDialog();
file.Filter = "文档(*.xls)|*.xls|文档(*.xlsx)|*.xlsx";
if (file.ShowDialog() == DialogResult.OK) filepath = file.FileName;
string fileNameWithoutExtension = System.IO.Path.GetDirectoryName(filepath);// 没有扩展名的文件名 “Default”
//判断有没有文件导入
if (file.FileName.Length == 0)
{
MessageBox.Show("请选择要导入的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
DataSet ds = new DataSet();
DataTable dt = new DataTable();
////改变了原来的逻辑,直接从中间表导出数据Excel,ADDBYxingkai
// dt = Liveflow.HaiKang.ExcelHelper.ExcelToDataTable(filePath, 1, 27, -1, 0, 1);
//把excel表数据读取到DataTable中
string strConn = string.Empty;
string excelName = SheetType;
//注意:把一个excel文件看做一个数据库,一个sheet看做一张表。语法 "SELECT * FROM [sheet1$]",表单要使用"[]"和"$"
// 1、HDR表示要把第一行作为数据还是作为列名,作为数据用HDR=no,作为列名用HDR=yes;
// 2、通过IMEX=1来把混合型作为文本型读取,避免null值。
// 3、判断是xls还是xlsx
string[] sArray = filepath.Split('.');
if (sArray[1].ToString() == "xls")
{
// strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1';";
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"; // Office 07及以上版本 不能出现多余的空格 而且分号注意
//dt = HRManageXls(strConn, excelName, SheetType, fileNameWithoutExtension, rowValue, ColumnValue);
}
else if (sArray[1].ToString() == "xlsx")
{
strConn = "Provider=Microsoft.Ace.OleDb.12.0;data source='" + filepath + "';Extended Properties='Excel 12.0; HDR=NO; IMEX=1';";
HRManageXlsX(strConn, excelName, SheetType, fileNameWithoutExtension, rowValue, ColumnValue);
}
}

  

3)读取excel文档中的数据 转换为datatable

public static void  HRManageXlsX(string strConn, string excelName,string SheetType,string fileNameWithoutExtension, string rowValue, string ColumnValue)
{
DataTable dt = new DataTable();
dt=GetCsvToDataTable(strConn, excelName, SheetType,rowValue, ColumnValue);//获取excel数据
//指定源列和目标列之间的对应关系
int row = dt.Rows.Count;//exce数据总行
int col = dt.Columns.Count;//excel数据总列
//生成两张txt
for (int i = 0; i < row; i++)
{
if (i >= 2) {
if (!string.IsNullOrEmpty(dt.Rows[i][0].ToString()))
{
//总公司QuotaSQl.txt
string QuotaSQl = "INSERT INTO dbo.TB_HR_SatisfactionEvaluation_Quota(IId,EvaluationYear , EvaluationType , LocationName ,DescVal ,DeptName ,EvaluationDesc ,enable ,createby ,CreateTime ,updateby ,updateTime)VALUES (" + dt.Rows[i][4].ToString() + ",'2018', '" + dt.Rows[i][0].ToString() + "','" + dt.Rows[i][0].ToString() + "', '" + dt.Rows[i][2].ToString() + "','" + dt.Rows[i][1].ToString() + "','" + dt.Rows[i][3].ToString().Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "") + "', 1,'',GETDATE(),'' ,GETDATE());";
WriteLog(QuotaSQl, "总公司QuotaSQl", fileNameWithoutExtension);
} if (!string.IsNullOrEmpty(dt.Rows[i][4].ToString()))
{
for (int j = 5; j < col; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
{
//总公司UserSQl.txt
string UserSQl = "INSERT INTO dbo.TB_HR_SatisfactionEvaluation_Quota_User( EvaluationYear ,QuotaID ,QuotoDept ,Quoter ,enable ,createby , CreateTime ,updateby ,updateTime ,Dept)VALUES ('2018','" + dt.Rows[i][4].ToString() + "','" + dt.Rows[0][j].ToString() + "','" + dt.Rows[i][j].ToString() + "',1,'sa',GETDATE(),'',GETDATE(),'');";
WriteLog(UserSQl, "总公司UserSQl", fileNameWithoutExtension);
}
}
}
}
} MessageBox.Show("读取信息完毕,已导出txt文件;路径为"+ fileNameWithoutExtension + "", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

  

4)关键方法

public static DataTable GetCsvToDataTable(string strConn, string excelName, string FillName, string rowValue, string ColumnValue)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
System.Data.OleDb.OleDbDataAdapter odda = new System.Data.OleDb.OleDbDataAdapter(string.Format("select * from [" + excelName + "$"+ rowValue + ":"+ ColumnValue + "]"), conn); //这里的表名参数,就是 CSV的完整文件名
odda.Fill(ds, FillName);
conn.Close();
return ds.Tables[0];
}

  

5)写入txt

/// <summary>
/// 写入日志
/// </summary>
/// <param name="logstr">写入的内容</param>
public static void WriteLog(string logstr,string Txtname,string fileNameWithoutExtension)
{
string strFileName = fileNameWithoutExtension+"/"+Txtname+ ".txt";
using (FileStream fs = new FileStream(strFileName, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
//声明数据流文件写入方法
sw.WriteLine(logstr);
sw.Close();
fs.Close();
}
}
}

  

c# 读取 excel文件内容,写入txt文档的更多相关文章

  1. 20130317 如何批量把文件名称写入txt文档

    1.如何批量把文件名称写入txt文档 COMMAND 窗口例:存放图片的文件夹是 D:\123\就用下面一名命令就OKdir d:\123\*.jpg /b > A.TXT 那么你所以JPG格式 ...

  2. C# 将内容写入txt文档

    <1>  FileStream fs = new FileStream(@"D:\text.txt", FileMode.Append); StreamWriter s ...

  3. IO流查找文件然后写入TXT文档

    今天领导让分析日志,把日志中所有登录过的员工信息都拿出来.于是.把日志摘下来谢了这段代码 import java.io.BufferedReader;import java.io.BufferedWr ...

  4. 使用POI读取excel文件内容

    1.前言 项目中要求读取excel文件内容,并将其转化为xml格式.常见读取excel文档一般使用POI和JExcelAPI这两个工具.这里我们介绍使用POI实现读取excel文档. 2.代码实例: ...

  5. PHP读取Excel文件内容

    PHP读取Excel文件内容   项目需要读取Excel的内容,从百度搜索了下,主要有两个选择,第一个是PHPExcelReader,另外一个是PHPExcel.   PHPExcelReader比较 ...

  6. 一个简易的Python爬虫,将爬取到的数据写入txt文档中

    代码如下: import requests import re import os #url url = "http://wiki.akbfun48.com/index.php?title= ...

  7. 关于jquery js读取excel文件内容 xls xlsx格式 纯前端

    附带参考:http://blog.csdn.net/gongzhongnian/article/details/76438555 更详细导入导出:https://www.jianshu.com/p/7 ...

  8. java实现读取excel文件内容

    package excel; import java.io.FileInputStream; import java.io.InputStream; import java.text.SimpleDa ...

  9. C语言,产生一组数字,并将其写入txt文档中

    #include<stdio.h> /*产生一组连续的数字,并将其写到txt文档中*/ /*说明:本程序在在win10 系统64位下用Dev-C++ 5.11版本编译器编译的*/int m ...

随机推荐

  1. dva基本用法

    1. npm install -g dva-cli 全局安装dva.2. dva new myApp --demo 创建dva项目.3. cd myApp npm start 启动项目.4. 定义 m ...

  2. 经典C语言编程注意点

    C/C++程序员应聘试题剖析 分中的2分.读者可从本文看到strcpy函数从2分到10分解答的例子,看看自己属于什么样的层次.此外,还有一些面试题考查面试者敏捷的思维能力. 分析这些面试题,本身包含很 ...

  3. 实现图像剪裁 jquery.Jcrop

       配合 jquery.Jcrop 实现上传图片进行剪裁保存功能    <script src="js/jquery.min.js"></script> ...

  4. [Transducer] Make an Into Helper to Remove Boilerplate and Simplify our Transduce API

    Our transduce function is powerful but requires a lot of boilerplate. It would be nice if we had a w ...

  5. SqlServer 错误日志切换和查看

    Sql Server 日志 和 代理错误日一般在实例重新启动后自己主动切换,假设实例久未重新启动,将可能积累太多的日志,不方便查看. 查看错误日志大小: --查看日志大小 EXEC xp_enumer ...

  6. List of content management systems

    https://en.wikipedia.org/wiki/List_of_content_management_systems Microsoft ASP.NET Name Platform Sup ...

  7. android取高度

    Rect rect = new Rect();  getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);  int top = r ...

  8. Where to Store your JWTs – Cookies vs HTML5 Web Storage--转

    原文地址:https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage Update 5/12/20 ...

  9. Hadoop框架基础(一)

    ** Hadoop框架基础(一)     学习一个新的东西,传统而言呢,总喜欢漫无目的的扯来扯去,比如扯扯发展史,扯扯作者是谁,而我认为这些东西对于刚开始接触,并以开发为目的学者是没有什么帮助的,反而 ...

  10. PostgreSQL Replication之第二章 理解PostgreSQL的事务日志(1)

    在前面的章节中,我们已经理解了各种复制概念.这不仅仅是一个为了接下来将要介绍的东西而增强您的意识的理论概述,还将为您介绍大体的主题. 在本章,我们将更加接近实际的解决方案,并了解PostgreSQL内 ...