I am trying to write to datatable to excel which has large records. I am trying to achieve using divide and conquer strategy where each thread is assigned to write to respective sheets of excelworkbook.but I am getting file is readonly ,click Ok to override the file.
class Program
{
int processorCount = 2;
static volatile bool processing = true;
DataTable employeeTable = new DataTable("Employee");
ManualResetEvent mre = new ManualResetEvent(false);
AutoResetEvent ar = new AutoResetEvent(true);
int record_count;
static void Main(string[] args)
{
Program p = new Program();
//Create an Emplyee DataTable
p.employeeTable.Columns.Add("Employee ID");
p.employeeTable.Columns.Add("Employee Name");
for (int i = 0; i <= 2; i++)
{
p.employeeTable.Rows.Add(i.ToString(), "ABC");
}
p.record_count = p.employeeTable.Rows.Count / p.processorCount;
Excel.Application excelApp = new Excel.Application();
//Create an Excel workbook instance and open it from the predefined location
Excel.Workbook excelWorkBook1 = excelApp.Workbooks.Open(@"F:\Org.xlsx");
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
// p.ExportDataSetToExcel(i);
ParameterizedThreadStart ps = new ParameterizedThreadStart(p.ExportDataSetToExcel);
threads[i] = new Thread(ps);
threads[i].Start(new Custom() { sheetNo = i, excelWorkBook = excelWorkBook1 });
}
for (int j = 0; j < 3; j++)
{
threads[j].Join();
}
Console.WriteLine("Succeess");
Console.ReadKey();
}
private void ExportDataSetToExcel(object sheet1)
{
lock (this)
{
bool found = false;
Excel.Worksheet excelWorkSheet;
int sheetNo = ((Custom)sheet1).sheetNo;
Excel.Workbook excelWorkBook = ((Custom)sheet1).excelWorkBook;
excelWorkSheet = (excelWorkBook).Sheets["Sheet" + ((int)sheetNo + 1).ToString()];
for (int i = 1; i < employeeTable.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = employeeTable.Columns[i - 1].ColumnName;
}
int baseIndex = (int)sheetNo * record_count;
for (int j = baseIndex; j < baseIndex + record_count; j++)
{
for (int k = 0; k < employeeTable.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = employeeTable.Rows[j].ItemArray[k].ToString();
}
}
Console.WriteLine(sheetNo.ToString());
Console.WriteLine("\n");
(excelWorkBook).Save();
(excelWorkBook).Close();
}
}
}**strong text**
public class Custom
{
public int sheetNo;
public Excel.Workbook excelWorkBook;
}