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

C#读取EXCEL模版方法

2012-08-14 20:04 369 查看
//读取EXCEL模版

FileStream fs = new FileStream(tempName, FileMode.OpenOrCreate, FileAccess.ReadWrite);

HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);

ISheet sheet = hssfworkbook.GetSheetAt(0);

//向Excel模版写标题

sheet.GetRow(Convert.ToInt16(indexCaption[0])).GetCell(Convert.ToInt16(indexCaption[1])).SetCellValue(tmpReportDate);

DataTable dt = new DataTable();

//连接数据库

SqlConnection sqlconn = new SqlConnection(DbProvider.ConnectionString);

SqlCommand sqlcomm = sqlconn.CreateCommand();

sqlconn.Open();

sqlcomm.CommandType = CommandType.StoredProcedure;

sqlcomm.Parameters.Add("@pmDate", SqlDbType.NVarChar).Value = curDate;

sqlcomm.Parameters.Add("@pmProductCode", SqlDbType.NVarChar).Value = "";

sqlcomm.Parameters.Add("@pmBranchCode", SqlDbType.NVarChar).Value = "";

if (IndexSystemID.Length > 0) sqlcomm.Parameters.Add("@pmSystemCode", SqlDbType.NVarChar).Value = "";

sqlcomm.Parameters.Add("@pmLX", SqlDbType.NVarChar).Value = "";

for (int s = 0; s < storeName.Length; s++)

{

sqlcomm.Parameters["@pmProductCode"].Value = indexProductID[s];

sqlcomm.Parameters["@pmBranchCode"].Value = indexBranchID[s];

if (IndexSystemID.Length > 0) sqlcomm.Parameters["@pmSystemCode"].Value = IndexSystemID[s];

sqlcomm.Parameters["@pmLX"].Value = pmType;

sqlcomm.CommandText = storeName[s];

dt.Load(sqlcomm.ExecuteReader());

if (dt.Rows.Count > 0)

{

int i = 0,j;

for (int r = Convert.ToInt16(indexLocation[s * 4]); r < dt.Rows.Count + Convert.ToInt16(indexLocation[s * 4]); r++, i++)

{

j = 0;

IRow row = sheet.GetRow(r);

for (int col = Convert.ToInt16(indexLocation[s * 4 + 2]); col < Convert.ToInt16(indexLocation[s * 4 + 2]) + Convert.ToInt16(indexLocation[s * 4 + 3]); col++, j++)

row.GetCell(col).SetCellValue(dt.Rows[i][j].ToString());

}

}

//将DataTable清空,如果不清空将会导致dt的数据累计

dt.Clear();

}

//把工作簿写入文件

using (FileStream wfs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))

{

hssfworkbook.Write(wfs);

wfs.Close();

//downFile(fileName);

}

sqlconn.Close();

hssfworkbook.Dispose();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: