以下是自己在近期学期中整理的静态类,里面有导出导入excel数据的一些方法
希望可以帮助到大家
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data;
using System.Runtime.InteropServices;
using System.IO;
namespace PartOfJRSpace.DataHelper
{
static class Datahelp
{
#region//选择文件,返回文件路径
public static string SelectFilePath()
{
string path = "";
using (SaveFileDialog sfd = new SaveFileDialog())
{
if (sfd.ShowDialog() == DialogResult.OK)
{
sfd.Title = "选择数据文件";
path = sfd.FileName;
return path;
}
}
return path;
}
#endregion
#region//获取excel中对应的datatable
public static DataTable ExcelToDS(string Path)
{
DataTable dt = null;
DataSet ds = null;
try
{
//filetype="xls"
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties= 'Excel 8.0;HDR=Yes;'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
DataTable midDt = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
OleDbDataAdapter myCommand = null;
//获得excel第一个表的名称
string tablename = midDt.Rows[0]["Table_Name"].ToString();
strExcel = string.Format("select * from [{0}]", tablename);
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1");
dt = ds.Tables["table1"];
}
catch(Exception ex)
{
throw;
}
return dt;
}
#endregion
#region//获取datatable里面的所有列名
public static string[] GetColName(DataTable dt)
{
string[] cName = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
cName[i] = dt.Columns[i].ColumnName;
}
return cName;
}
#endregion
#region//创建excel文件
public static string CreateExcel(DataTable dt)
{
string path = "";
return path;
}
#endregion
#region//选择指定列名的datatable
public static DataTable GetAppointData(string[] cName,DataTable dt)
{
DataTable mid = new DataTable();
DataColumn dc;
for (int i = 0; i < cName.Length; i++)
{
dc = new DataColumn();
dc.ColumnName=cName[i];
mid.Columns.Add(dc);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = mid.NewRow();
for (int j = 0; j < cName.Length; j++)
{
dr[cName[j]] = dt.Rows[i].ItemArray[dt.Columns.IndexOf(cName[j])];
//MessageBox.Show(dr[cName[j]].ToString());
}
mid.Rows.Add(dr);
}
return mid;
}
#endregion
#region//将datatable存入excel中
//public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int pid);
//函数原型;DWORD GetWindowThreadProcessld(HWND hwnd,LPDWORD lpdwProcessld);
//参数:hWnd:窗口句柄
//参数:lpdwProcessld:接收进程标识的32位值的地址。如果这个参数不为NULL,GetWindwThreadProcessld将进程标识拷贝到这个32位值中,否则不拷贝
//返回值:返回值为创建窗口的线程标识。
//dt:从数据库读取的数据;file_name:保存路径;sheet_name:表单名称
public static void DataTableToExcel(DataTable dt, string file_name)
{
string path;
Microsoft.Office.Interop.Excel.Application Myxls = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook Mywkb = Myxls.Workbooks.Add();
Microsoft.Office.Interop.Excel.Worksheet MySht = Mywkb.ActiveSheet;
//MySht.Name = sheet_name;
Myxls.Visible = false;
Myxls.DisplayAlerts = false;
try
{
//写入表头
object[] arrHeader = new object[dt.Columns.Count];
for(int i = 0; i < dt.Columns.Count; i++)
{
arrHeader[i] = dt.Columns[i].ColumnName;
}
MySht.Range[MySht.Cells[1, 1], MySht.Cells[1, dt.Columns.Count]].Value2 = arrHeader;
//写入表体数据
object[,] arrBody = new object[dt.Rows.Count, dt.Columns.Count];
for(int i = 0; i < dt.Rows.Count; i++)
{
for(int j = 0; j < dt.Columns.Count; j++)
{
arrBody[i,j] = dt.Rows[i][j].ToString();
}
}
MySht.Range[MySht.Cells[2,1], MySht.Cells[dt.Rows.Count + 1, dt.Columns.Count]].Value2 = arrBody;
if(Mywkb != null)
{
Mywkb.SaveAs(file_name);
Mywkb.Close(Type.Missing, Type.Missing, Type.Missing);
Mywkb = null;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "系统提示");
}
finally
{
GC.Collect();
}
}
#endregion
#region//读取CSV文件到datatable
public static DataTable GetTableFromCsv(string csvPath)
{
System.Data.DataTable dt = new System.Data.DataTable();
FileStream fs = new FileStream(csvPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
//Unicode存储,列之间使用tab间隔
//StreamReader sr = new StreamReader(fs, new System.Text.UnicodeEncoding());
//utf - 8存储,使用逗号间隔
StreamReader sr = new StreamReader(fs, new System.Text.UTF8Encoding());
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
//aryLine = strLine.Split('\t');
aryLine = strLine.Split(',');
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i]);
dt.Columns.Add(dc);
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}
sr.Close();
fs.Close();
return dt;
}
#endregion
#region//将datatable导出至CSV
public static void DataTableCSV(System.Data.DataTable dt, string AbosultedFilePath)
{
FileStream fs = new FileStream(AbosultedFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
string data = "";
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
data += dt.Rows[i][j].ToString();
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
}
private static string DelQuota(string str)
{
string result = str;
string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
for (int i = 0; i < strQuota.Length; i++)
{
if (result.IndexOf(strQuota[i]) > -1)
result = result.Replace(strQuota[i], "");
}
return result;
}
#endregion
#region//字符串转二进制(加密)
public static string StringToBinary(string s)
{
byte[] data = Encoding.Unicode.GetBytes(s);
StringBuilder result = new StringBuilder(data.Length * 8);
foreach (byte b in data)
{
result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
return result.ToString();
}
#endregion
# region//二进制转String(解密)
public static string BinaryToString(string s)
{
System.Text.RegularExpressions.CaptureCollection cs =
System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures;
byte[] data = new byte[cs.Count];
for (int i = 0; i < cs.Count; i++)
{
data[i] = Convert.ToByte(cs[i].Value, 2);
}
return Encoding.Unicode.GetString(data, 0, data.Length);
}
#endregion
/// <summary>
/// A字符串替换文本的B字符串
/// </summary>
/// <param name="path"></param>
/// <param name="A"></param>
/// <param name="B"></param>
public static void Rreplace(string path,string A,string B)
{
string con = "";
FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fsread);
con = sr.ReadToEnd();
con = con.Replace("$OpenData$", A);//数据路径替换
con = con.Replace("$SaveData$", B);//结果路径替换
sr.Close();
fsread.Close();
FileStream fswrite = new FileStream(path, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fswrite);
sw.WriteLine(con);
sw.Close();
fswrite.Close();
}
/// <summary>
/// 复制文件,A复制至B
/// </summary>
public static void CopyFile(string pathA,string pathB)
{
string sourceFile = pathA;
string destinationFile = pathB;
if (File.Exists(sourceFile))
{
// true is overwrite
File.Copy(sourceFile, destinationFile, true);
}
}
/// <summary>
/// 删除该路径对应的文件
/// </summary>
/// <param name="path"></param>
public static void DeleteFile(string path)
{
string fileToBeDeleted = path;
if (File.Exists(fileToBeDeleted))
{
File.Delete(fileToBeDeleted);
}
}
}
}