c#读Excel的问题?
public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
// get Excel DataSet
}
我采用这种方法,连接了Excel,并可以获得Excel中Cell的值。
但是用这种方法链接Excel,怎么读excel中文本框(Textbox)的值?
求指导!!!!!!
有源码更好!
对好心人致礼!
------解决方案--------------------
可类似参考
http://www.tech-archive.net/Archive/Office/microsoft.public.office.developer.automation/2006-10/msg00007.html
http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/cb179a3f-cfd4-4762-9c52-60d248024436/
------解决方案--------------------
/// <summary>读取excel
/// 默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
NPOI.SS.UserModel.Sheet sheet = hssfworkbook.GetSheetAt(0);
//HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
//HSSFRow headerRow = sheet.GetRow(0);
//NPOI.SS.UserModel.Row headerRow = sheet.GetRow(0);
//int cellCount = headerRow.LastCellNum;
NPOI.SS.UserModel.Row headerrow = sheet.GetRow(sheet.FirstRowNum + 2);
int cellCount = headerrow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
//HSSFCell cell = headerRow.GetCell(j);
NPOI.SS.UserModel.Cell cell = headerrow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 3); i <= sheet.LastRowNum; i++)
{
//HSSFRow row = sheet.GetRow(i);
NPOI.SS.UserModel.Row row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString().Replace("_","");
}
dt.Rows.Add(dataRow);
}
return dt;
}