您的位置:首页 > 编程语言 > C#

c#里excel转换成csv的万能方法

2012-04-01 10:27 267 查看
最近搞了半天,都搞不定excel转换问题,总算找到一个ExcelWrapper.dll,直接在机子里面打开excel,然后读取cell,读好后把cell内容整理好,转换成csv格式。好了废话少说,下面的是我写的转换类

OleDb连接方法

static void convertExcelToCSV(string sourceFile, string worksheetName, string targetFile)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";

OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataAdapter da = null;

try
{
conn = new OleDbConnection(strConn);
conn.Open();

//cmd = new OleDbCommand("SELECT * FROM " + worksheetName, conn);
cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
cmd.CommandType = CommandType.Text;
wrtr = new StreamWriter(targetFile);

da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);

for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
Console.WriteLine();
Console.WriteLine("Done! Your " + sourceFile + " has been converted into " + targetFile+".");
Console.WriteLine();
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
Console.ReadLine();
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
wrtr.Close();
wrtr.Dispose();
}
}


主要不兼容64位模式,折腾了好久,这次总算解决了!

文件这样上传,不知道对不对
http://files.cnblogs.com/grey/ExcelWrapper.zip
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐