码迷,mamicode.com
首页 > 其他好文 > 详细

Excel 导入支持csv

时间:2014-05-09 11:03:31      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:tar   int   c   get   文件   string   

/// <summary>
/// 根据Excel转换成DataTable
/// </summary>
/// <param name="FileName">文件名称</param>
/// <returns></returns>
private System.Data.DataTable getTableByExecl(string FileName)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
object oMissing = System.Reflection.Missing.Value;//相当null
workbook = excel.Workbooks.Open(FileName, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
worksheet = (Worksheet)workbook.Worksheets[1];
int rowCount = worksheet.UsedRange.Rows.Count;
int colCount = worksheet.UsedRange.Columns.Count;
Microsoft.Office.Interop.Excel.Range range1;
System.Data.DataTable dt = new System.Data.DataTable();
for (int i = 0; i < colCount; i++)
{
range1 = worksheet.get_Range(worksheet.Cells[1, i + 1], worksheet.Cells[1, i + 1]);
if (range1.Value2 == null)
{
dt.Columns.Add("");
continue;
}
dt.Columns.Add(range1.Value2.ToString());
}
for (int j = 0; j < rowCount; j++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < colCount; i++)
{
range1 = worksheet.get_Range(worksheet.Cells[j + 1, i + 1], worksheet.Cells[j + 1, i + 1]);
dr[i] = range1.Value2 == null ? "" : range1.Value2.ToString();
}
dt.Rows.Add(dr);
}
excel.Quit();
return dt;
}

Excel 导入支持csv,布布扣,bubuko.com

Excel 导入支持csv

标签:tar   int   c   get   文件   string   

原文地址:http://www.cnblogs.com/mingxuantongxue/p/3709134.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!