您的位置:首页 > 其它

将实体对象集合数据写入Excel的通用类

2008-08-14 12:26 344 查看
好久没更新博客了!发一个实用的Excel工具类,用来将实体类集合写入到Excel,并且可以设定Excel中列规则,包括是否可以编辑,是否允许重复值。下面是完整代码,主函数里内容为使用说明。DataObject是演示用的一个测试实体类,ExcelWriter和PropertyInfo是主要的类。别忘了加上对Excel程序集的引用

public class ExcelReader

{

private Excel.Application application;

private Excel.Workbook workbook;

private Excel.Worksheet worksheet;

private object missing = Type.Missing;

private string filePath = "";

public ExcelReader(string filePath)

{

this.filePath = filePath;

}

/// <summary>

/// 验证文件隐藏Sheet中保存的文件批号是否和要求的一致

/// </summary>

/// <param name="rightSN"></param>

private void ValidateFileSN(string rightSN)

{

//读取隐藏Sheet中的文件批号

application = new Excel.Application();

workbook = application.Workbooks.Open(filePath, missing, missing, missing, missing,

missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);

worksheet = workbook.Sheets.get_Item("HiddenSheet") as Excel.Worksheet;

Excel.Range firstRange = worksheet.get_Range("A1", "A1");

string fileSN = firstRange.get_Value(missing).ToString();

//退出并关闭Excel

workbook.Close(missing, missing, missing);

application.Quit();

ExcelWriter.KillExcelProcess(application);

//验证批号

if (fileSN != rightSN)

{

throw new Exception("文件批号不正确!");

}

}

/// <summary>

/// 从Excel中读取数据到DataTable如果rightSN为null则不检查文件批号

/// </summary>

/// <param name="rightSN"></param>

/// <returns></returns>

public DataTable ReadDataFromExcel(string rightSN)

{

//验证文件批号

if (rightSN != null)

{

ValidateFileSN(rightSN);

}

//读取Excel数据到DataTable

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";

OleDbConnection conn = new OleDbConnection(strConn);

string strExcel = "";

OleDbDataAdapter myCommand = null;

DataSet ds = new DataSet();

strExcel = "select * from [sheet1$]";

try

{

conn.Open();

myCommand = new OleDbDataAdapter(strExcel, strConn);

myCommand.Fill(ds, "dtSource");

return ds.Tables[0];

}

catch

{

return null;

}

finally

{

conn.Close();

conn.Dispose();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐