Step of reading data from excel sheet and insert into database.
Step 1: Open .Net and Select New Project=> and Select SharePoint 2010=>Visual Web Part.
Step 2: Open the .cs file and put this code.
This code is for generate Xml for insert in databse:-
private string
GetXMLFromExcel(System.Web.HttpPostedFile
file)
{
string
savePath = string.Empty;
string
xmlData = string.Empty;
string
dirPath = string.Empty;
dirPath =
Path.Combine(Request.PhysicalApplicationPath,
"BAUBUG");
savePath =
Path.Combine(dirPath, file.FileName);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
FUExcelSheet.PostedFile.SaveAs(savePath);
xmlData = ReadDataFromExcel(savePath,
file.FileName);
System.IO.File.Delete(savePath);
return
xmlData;
}
This code return xml String code of Excel:-
public string
ReadDataFromExcel(string filePath,
string fileName)
{
DataSet dataSet =
null;
OleDbConnection oledbConn =
null;
OleDbCommand command =
null;
OleDbDataAdapter dataAdapter =
null;
string strConnectionString =
null;
try
{
strConnectionString =
ExcelProvider(fileName).ToString() + "Data Source="
+ filePath + ExtendedProperties(fileName);
oledbConn = new
OleDbConnection(strConnectionString);
// Opens OleDb Connection
oledbConn.Open();
string excelSheetName =
oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
null)
.Rows[0]["TABLE_NAME"].ToString().Replace("'",
"");
// Create OleDbCommand object and select data from worksheet
Sheet1
command = new
OleDbCommand("SELECT
* FROM [" + excelSheetName + "]",
oledbConn);
// Create new OleDbDataAdapter
dataAdapter = new
OleDbDataAdapter(command);
// Create a DataSet which will hold the data extracted from the
worksheet.
dataSet = new
DataSet("Root");
// Fill the DataSet from the data extracted from the worksheet.
dataAdapter.Fill(dataSet, "Detail");
//foreach (DataRow dr in dataSet.Tables[0].Rows)
//{
Join the conversation! Your thoughts help the community grow.