Read Excel
ClosedXML:
public static DataTable getExcelDatas(string FullFileName)
{
try
{
using (XLWorkbook workBook = new XLWorkbook(@FullFileName))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(1);
//Create a new DataTable.
DataTable dt = new DataTable();
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
firstRow = false;
}
else
{
//Add rows to DataTable.
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells(row.FirstCellUsed().Address.ColumnNumber, row.LastCellUsed().Address.ColumnNumber))
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
}
return dt;
}
}
catch (Exception ex)
{
MessageBox.Show("Close your Excel File.");
return null;
}
OleDb:
public static DataTable ExcelConnect(string FullFileName)
{
DataTable dt = new DataTable();
DataSet ds = new DataSet();
try
{
string FileName = "";
FileName = Path.GetFileNameWithoutExtension(FullFileName);
//string name = "Sheet1";
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FullFileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
//string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FullFileName + ";Extended Properties=Excel 8.0;HDR=YES;IMEX=1';";
OleDbConnection con = new OleDbConnection(constr);
con.Open();
DataTable schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
OleDbCommand oconn = new OleDbCommand("select * from [" + schemaTable.Rows[0]["TABLE_NAME"] + "]", con);
//OleDbCommand oconn = new OleDbCommand("select * from [" + name + "$]", con);
//on.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
adp.Fill(dt);
con.Close();
}
catch (Exception ex)
{
//con.Close();
Console.WriteLine(ex.ToString());
MessageBox.Show("Failed to read excel" + ex.ToString());
}
}
Write Excel
public static string CopyFormatFile(string saveFilePath, string fileName)
{
string time = DateTime.Now.ToString("yyyyMMdd"); ;
string formatPath = Application.StartupPath + "\\W2W Format Location.xlsx";
string copyFormatPath = saveFilePath + "\\" + time + "_" + fileName + ".xlsx";
File.Copy(formatPath, copyFormatPath, true);
return copyFormatPath;
}
public static void makeExcel(string fullFileName, string sheetName, List<ExcelDto> listDto)
{
var workbook = new XLWorkbook(@fullFileName);
IXLWorksheet sheet = workbook.Worksheet(1);
int row = 5;
for (int i = 0; i < listDto.Count; i++)
{
//TAG ID
sheet.Cell(row, 2).Value =listDto[i].TAG_ID;
row = row + 1;
}
workbook.SaveAs(fullFileName);
}