How to append existing excel file using C# - c#

Below are my code, I'm stuck with can't append the contents in the excel,
When first time load the program, the excel can output normal
But at Second time load the program, the excel will crash badly(can't open).
I'm using the FileMode.Append, FileAccess.Write, but still can't works
Is there have some step I missed it? please help me to solve this issue, thanks a lot!
XSSFWorkbook XSSFworkbook = new XSSFWorkbook(); //建立活頁簿
ISheet sheet = XSSFworkbook.CreateSheet(tbx_Build.Text); //建立sheet
//設定樣式
ICellStyle headerStyle = XSSFworkbook.CreateCellStyle();
IFont headerfont = XSSFworkbook.CreateFont();
headerStyle.Alignment = HorizontalAlignment.Center; //水平置中
headerStyle.VerticalAlignment = VerticalAlignment.Center; //垂直置中
headerfont.FontName = "Segoe UI";
headerfont.FontHeightInPoints = 12;
headerfont.Boldweight = (short)FontBoldWeight.Bold;
headerStyle.SetFont(headerfont);
XSSFCellStyle cs = (XSSFCellStyle)XSSFworkbook.CreateCellStyle();
cs.WrapText = true; // 設定換行
cs.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Top;
//新增標題列
IRow headerrow = sheet.CreateRow(0);//建立行
headerrow.HeightInPoints = 20;
headerrow.CreateCell(0).SetCellValue("System_name");
headerrow.CreateCell(1).SetCellValue("Fixture_name");
headerrow.CreateCell(2).SetCellValue("build_ID");
headerrow.CreateCell(3).SetCellValue("start_time");
headerrow.CreateCell(4).SetCellValue("end_time");
headerrow.CreateCell(5).SetCellValue("serial_number");
headerrow.CreateCell(6).SetCellValue("Status");
headerrow.CreateCell(7).SetCellValue("Symptom_label");
headerrow.CreateCell(8).SetCellValue("Repair");
headerrow.CreateCell(9).SetCellValue("Measurement");
headerrow.CreateCell(10).SetCellValue("Board_slot");
headerrow.CreateCell(11).SetCellValue("Error");
headerrow.CreateCell(12).SetCellValue("Version");
for (int i = 0; i < 13; i++)
{
headerrow.GetCell(i).CellStyle = headerStyle; //套用樣式
}
//填入資料
int rowIndex = 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(rowIndex);//建立行
row.HeightInPoints = 18;
row.CreateCell(0).SetCellValue(Convert.ToString(dt.Rows[i]["System_name"]));
row.CreateCell(1).SetCellValue(Convert.ToString(dt.Rows[i]["Fixture_name"]));
row.CreateCell(2).SetCellValue(Convert.ToString(dt.Rows[i]["build_ID"]));
row.CreateCell(3).SetCellValue(Convert.ToString(dt.Rows[i]["start_time"]));
row.CreateCell(4).SetCellValue(Convert.ToString(dt.Rows[i]["end_time"]));
row.CreateCell(5).SetCellValue(Convert.ToString(dt.Rows[i]["serial_number"]));
row.CreateCell(6).SetCellValue(Convert.ToString(dt.Rows[i]["Status"]));
row.CreateCell(7).SetCellValue(Convert.ToString(dt.Rows[i]["Symptom_label"]));
row.CreateCell(8).SetCellValue(Convert.ToString(dt.Rows[i]["Repair"]));
row.CreateCell(9).SetCellValue(Convert.ToString(dt.Rows[i]["Measurement"]));
row.CreateCell(10).SetCellValue(Convert.ToString(dt.Rows[i]["Board_slot"]));
row.CreateCell(11).SetCellValue(Convert.ToString(dt.Rows[i]["Error"]));
row.CreateCell(12).SetCellValue(Convert.ToString(dt.Rows[i]["Version"]));
if (dt.Rows[i]["Error"].ToString().Contains("\n"))
{
row.GetCell(12).CellStyle = cs;
row.HeightInPoints = 45;
}
else if (dt.Rows[i]["Repair"].ToString().Contains("\n"))
{
row.GetCell(12).CellStyle = cs;
row.HeightInPoints = 45;
}
sheet.AutoSizeColumn(i); //欄位自動調整大小
rowIndex++;
}
string newName2 = "Yield.xlsx";
string exportpath2 = server_backup_failed + "\\output";
if (!System.IO.Directory.Exists(exportpath2))
{
System.IO.Directory.CreateDirectory(exportpath2);//不存在就建立目錄
}
var file2 = new FileStream(exportpath2 + "\\" + newName2, FileMode.Append, FileAccess.Write);
XSSFworkbook.Write(file2, true);
file2.Close();
XSSFworkbook.Close();
}

As already commented… I can confirm from a few tests that …
FileMode.Append
Will not work as you are intending. This seems somewhat obvious since a workbook can have multiple worksheets and what you describe is appending the data to an existing worksheet… The FileStream will not know how to do this.
Therefore, as already described, you need to open the file, make the changes (append the rows) and then save the file and close it. In my tests this worked using most of your code with some minor changes. In your current code, it is always creating a “new” Excel workbook and worksheet. So if you want to “append” something to a worksheet, then that “implies” that the workbook and worksheet may already exists. So, if the workbook already exists, then we want to open it and not create a new one.
Therefore, I suggest a small method that takes a string file path and file name and returns a workbook. If the workbook exists, then we simply return the workbook. If the workbook does not exist, then we return a “new” workbook. If the path is bad or any other failure… we will return a null value. Something like…
private XSSFWorkbook GetExcelWorkbook(string filePath) {
if (!File.Exists(filePath)) {
return new XSSFWorkbook();
}
try {
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
return new XSSFWorkbook(fs);
}
}
catch (Exception ex) {
Debug.WriteLine("Excel Error getting workbook: " + ex.Message);
return null;
}
}
This should help getting the workbook. Next, It appears the code is looking for a “specific” worksheet. Similar to the code above a simple method that takes a workbook and a worksheet name and returns a worksheet with the given name may come in handy. Again, if the worksheet already exists, then we simply return that worksheet. If the worksheet does not exist, then we will create a new worksheet with the given name. In addition, we will go ahead and add the headers row if the worksheet is new. This is also in another method so that you could also add the header row each time new data is appended. However in this example, the header is added only when a new worksheet is created and assumes the header row already exist in existing files.
This method may look something like…
private ISheet GetWorksheet(XSSFWorkbook wb, string targetSheetName) {
try {
for (int i = 0; i < wb.NumberOfSheets; i++) {
if (wb.GetSheetAt(i).SheetName.Equals(targetSheetName)) {
return wb.GetSheetAt(i);
}
}
ISheet ws = wb.CreateSheet(targetSheetName);
AddHeaders(wb, ws);
return ws;
}
catch (Exception e) {
Debug.WriteLine("Excel Error getting worksheet: " + e.Message);
return null;
}
}
A walkthrough of the code above is straight forward… Loop through the given workbooks worksheets to look for the target worksheet name. If the worksheet is found it is returned. If the worksheet is not found, then a new worksheet is created with the target name, add the headers to the new worksheet then return the new worksheet. If some error arises a null value is returned.
Next is the method that adds the headers to the worksheet and is taken almost directly from your code.
private void AddHeaders(XSSFWorkbook wb, ISheet sheet) {
IRow headerrow = sheet.CreateRow(0);
headerrow.HeightInPoints = 20;
headerrow.CreateCell(0).SetCellValue("System_name");
headerrow.CreateCell(1).SetCellValue("Fixture_name");
headerrow.CreateCell(2).SetCellValue("build_ID");
headerrow.CreateCell(3).SetCellValue("start_time");
headerrow.CreateCell(4).SetCellValue("end_time");
headerrow.CreateCell(5).SetCellValue("serial_number");
headerrow.CreateCell(6).SetCellValue("Status");
headerrow.CreateCell(7).SetCellValue("Symptom_label");
headerrow.CreateCell(8).SetCellValue("Repair");
headerrow.CreateCell(9).SetCellValue("Measurement");
headerrow.CreateCell(10).SetCellValue("Board_slot");
headerrow.CreateCell(11).SetCellValue("Error");
headerrow.CreateCell(12).SetCellValue("Version");
ICellStyle headerStyle = wb.CreateCellStyle();
IFont headerfont = wb.CreateFont();
headerStyle.Alignment = HorizontalAlignment.Center;
headerStyle.VerticalAlignment = VerticalAlignment.Center;
headerfont.FontName = "Segoe UI";
headerfont.FontHeightInPoints = 12;
headerfont.Boldweight = (short)FontBoldWeight.Bold;
headerStyle.SetFont(headerfont);
for (int i = 0; i < 13; i++) {
headerrow.GetCell(i).CellStyle = headerStyle;
}
}
These methods should simplify “appending” data to an existing worksheet or creating a new worksheet. So, using the above methods, the code below works as described here… This code is added to a button clicks event. Initially, some test data is created for the DataTable dt that will be appended to the worksheet. Next, we check if the given folder path exists and if not, then create it.
Next we use our methods above to get the workbook and also the worksheet. The worksheet name is as you have in the current code and is coming from a TextBox ...tbx_Build on the form.
Next, instead of setting rowIndex to 1, we set it to the last row of existing data in the worksheet so we can “append” the data. Specifically the line…
int rowIndex = ws.LastRowNum + 1;
Next a cell style is created and a loop through the DataTables dt rows where each cell is added to the worksheet. Note I removed the unnecessary “Convert” code and used the cells ToString() method. And finally a style is added to some cells for some reason.
And lastly, the FilesStream is created to save the file and possibly overwrite it when it’s not new.
You may note, that the workbook wb is closed in the finally portion of the try/catch/finally statement and the reason for this is that if the code fails sometime after the workbook is open, then it may not get closed. This ensures that the workbook is properly closed.
private void button1_Click(object sender, EventArgs e) {
string workbookName = "__NewBook_1.xlsx";
string saveFilePath = #"D:\Test\Excel_Test";
DataTable dt = GetTable();
FillTable(dt);
XSSFWorkbook wb = null;
try {
if (!Directory.Exists(saveFilePath)) {
Directory.CreateDirectory(saveFilePath);
}
wb = GetExcelWorkbook(saveFilePath + #"\" + workbookName);
if (wb != null) {
ISheet ws = GetWorksheet(wb, tbx_Build.Text);
if (ws != null) {
int rowIndex = ws.LastRowNum + 1;
ICellStyle cs = wb.CreateCellStyle();
cs.WrapText = true;
cs.VerticalAlignment = VerticalAlignment.Top;
for (int i = 0; i < dt.Rows.Count; i++) {
IRow row = ws.CreateRow(rowIndex);
row.HeightInPoints = 18;
row.CreateCell(0).SetCellValue(dt.Rows[i]["System_name"].ToString());
row.CreateCell(1).SetCellValue(dt.Rows[i]["Fixture_name"].ToString());
row.CreateCell(2).SetCellValue(dt.Rows[i]["build_ID"].ToString());
row.CreateCell(3).SetCellValue(dt.Rows[i]["start_time"].ToString());
row.CreateCell(4).SetCellValue(dt.Rows[i]["end_time"].ToString());
row.CreateCell(5).SetCellValue(dt.Rows[i]["serial_number"].ToString());
row.CreateCell(6).SetCellValue(dt.Rows[i]["Status"].ToString());
row.CreateCell(7).SetCellValue(dt.Rows[i]["Symptom_label"].ToString());
row.CreateCell(8).SetCellValue(dt.Rows[i]["Repair"].ToString());
row.CreateCell(9).SetCellValue(dt.Rows[i]["Measurement"].ToString());
row.CreateCell(10).SetCellValue(dt.Rows[i]["Board_slot"].ToString());
row.CreateCell(11).SetCellValue(dt.Rows[i]["Error"].ToString());
row.CreateCell(12).SetCellValue(dt.Rows[i]["Version"].ToString());
if (dt.Rows[i]["Error"].ToString().Contains("\n")) {
row.GetCell(12).CellStyle = cs;
row.HeightInPoints = 45;
}
else if (dt.Rows[i]["Repair"].ToString().Contains("\n")) {
row.GetCell(12).CellStyle = cs;
row.HeightInPoints = 45;
}
ws.AutoSizeColumn(i);
rowIndex++;
}
using (FileStream fs = new FileStream(saveFilePath + #"\" + workbookName, FileMode.Create, FileAccess.Write)) {
wb.Write(fs, true);
}
}
}
}
catch (Exception ex) {
Debug.WriteLine("Excel Error: " + ex.Message);
}
finally {
if (wb != null) {
wb.Close();
}
}
}
And finally the code that creates some test data to test the above methods and complete the example.
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment;
private DataTable GetTable() {
DataTable dt = new DataTable();
dt.Columns.Add("System_name");
dt.Columns.Add("Fixture_name");
dt.Columns.Add("build_ID");
dt.Columns.Add("start_time");
dt.Columns.Add("end_time");
dt.Columns.Add("serial_number");
dt.Columns.Add("Status");
dt.Columns.Add("Symptom_label");
dt.Columns.Add("Repair");
dt.Columns.Add("Measurement");
dt.Columns.Add("Board_slot");
dt.Columns.Add("Error");
dt.Columns.Add("Version");
return dt;
}
private void FillTable(DataTable dt) {
for (int i = 0; i < 20; i++) {
dt.Rows.Add("C0R" + (i + 1), "C1R" + (i + 1), "C2R" + (i + 1), "C3R" + (i + 1), "C4R" + (i + 1),
"C5R" + (i + 1), "C6R" + (i + 1), "C7R" + (i + 1), "C8R" + (i + 1), "C9R" + (i + 1),
"C10R" + (i + 1), "C11R" + (i + 1), "C12R" + (i + 1));
}
}
I hope this makes sense. I tested this numerous times and it appears to work as expected, however there may still be some necessary exception checking that was not added for brevity. If something is not correct please let me know and I will correct it if possible.

Related

Save data from datagridview to excel file

i have created function to save data from datagridview to excel file.
Function to save :
try
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Records";
try
{
for (int i = 0; i < dataGridView2.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dataGridView2.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
if (dataGridView2.Rows[i].Cells[j].Value != null)
{
worksheet.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
}
else
{
worksheet.Cells[i + 2, j + 1] = "";
}
}
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Export Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
app.Quit();
workbook = null;
worksheet = null;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
And it works good on my computer with version :
I try to run this on my second computer where is installed :
What i need to change in code to works with both versions?
I'm looking example that will do the same but works on every office installation.
Btw when i try to run on second computer i have this error :
This isn't an answer directly to why your code throws that error. But as an alternative approach that works for me, could be worth trying? I used 'ClosedXML' package from Nuget... There are probably other options out there too like 'yob's reply, that I'm sure would also work fine.
using ClosedXML.Excel;
Then to save data:
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.Filter = "Excel file|*.xlsx";
saveFile1.Title = "save results as Excel spreadsheet";
saveFile1.FileName = title + " -" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
if (saveFile1.ShowDialog() == DialogResult.OK)
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add(data, title);
wb.SaveAs(saveFile1.FileName);
}
'data' is a datatable, so you would need to convert the datagridview to datatable first. As I said, not an answer to your existing code, but a possible alternative that works for me :) Good luck.
if you're not bound to use MS Office components, then I'd suggest to use EPPlus library instead.
string saveasFileName = .....
using (var package = new ExcelPackage())
{
using (var worksheet = package.Workbook.Worksheets.Add("Records"))
{
worksheet.Cells[1, 1].Value = "Records from dataGridView2:";
worksheet.Cells[1, 1].Style.Font.Bold = true;
// column headers
for (int i = 0; i < dataGridView2.Columns.Count; i++)
{
worksheet.Cells[2, i + 1].Value = dataGridView2.Columns[i].HeaderText;
}
// actual data
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
// ... populate worksheet ...
worksheet.Cells[i + 3, j + 1].Value = dataGridView2.Rows[i].Cells[j].Value?.ToString()??"";
}
}
// save
package.SaveAs(saveasFileName);
}
}
I have an example at https://github.com/siccolo/EppPlus_CreateExcel/blob/master/Excel.cs
#Adamszsz - if you need to open an excel file and load into gridview, then you can use oledb connection, for example: - open excel file .xls:
...
var excelconnection = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
var table = "[Sheet1$]"
// using System.Data.OleDb
var excel = new OleDbDataAdapter("SELECT * FROM " + table, excelconnection);
var exceldata = new DataTable();
excel.Fill(exceldata);
...
while for excel file .xlsx use Net.SourceForge.Koogra.Excel2007.

DataGridViewS export to excel sheetS

I want to export all my DataGridViews in one Excell document.
For every DataGridView there shoud be a own sheet in the Excell File.
But with my code i only recive the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"
I think there is something wrong with my parameters.
private void exportToExcellButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileD = new SaveFileDialog();
string fileName = truckListBox.SelectedItem.ToString() + "__" + DateTime.Now.ToShortDateString();
saveFileD.InitialDirectory = #"C:/TML/";
saveFileD.FileName = fileName;
if (!Directory.Exists(#"C:/TML/"))
Directory.CreateDirectory(#"C:/TML/");
List<DataGridView> dataGridViews = getAllDataGridViews();
Microsoft.Office.Interop.Excel.Application app;
Microsoft.Office.Interop.Excel.Workbook book;
Microsoft.Office.Interop.Excel.Worksheet sheet;
app = new Excel.Application();
app.Visible = true;
book = app.Workbooks.Add(System.Reflection.Missing.Value);
foreach (var grid in dataGridViews)
{
int count = book.Worksheets.Count;
sheet = (Worksheet)book.Sheets.Add(Type.Missing, book.Worksheets[count], Type.Missing, Type.Missing);
sheet.Name = grid.Name.ToString().Remove(0, 13);
int cMin = 0, rMin = 0;
int c = cMin, r = rMin;
// Set Headers
foreach (DataGridViewColumn column in grid.Columns)
{
//Here appears the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"
sheet.Cells[r, c] = column.HeaderText;
c++;
}
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].Font.Bold = true;
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Set Rows
foreach (DataGridViewRow row in grid.Rows)
{
r++;
c = cMin;
// Set Cells
foreach (DataGridViewCell item in row.Cells)
{
sheet.Cells[r, c++] = item.Value;
}
}
}
book.Save();
book.Close();
app.Quit();
}
Spended allready days into it and cant get it work.
Thx for your Help!
EDIT: Fixed one error to get to the new one.
There are a few problems you may have with the posted code. Therefore, I will break them down.
For starters, it appears you are using a SaveFileDialog however I do not see where it is being used. The code sets the InitalDirectory and FileName, but it is never used. This is not that important as a dialog is not really needed, however the way the code is getting the file name is going to have some problems. The line of code…
string fileName = truckListBox.SelectedItem.ToString() + "__" + DateTime.Now.ToShortDateString();
is going to have problems if you try to save the file name because the string returned from DateTime.Now.ToShortDateString() is going to be in a format like “2019\11\26”… Obviously the “\” characters are going to be interpreted as a path (folder) and will most likely fail when the code tries to save the file. Creating a method that returns a string that uses some other character should be easy to fix this.
Next is the fact that Excel files are NOT zero based on their rows and columns. Therefore, setting the initial Excel row column variables (int c = 0, r = 0;) will fail on the first try. These values should be one (1).
Another problem is on the line…
book.Save();
Is most likely going to save the file to the users “Documents” folder using the file name of “Book1.xlsx.” When saving the file you need to supply the complete path and file name which as stated earlier does not appear to be used.
Lastly, anytime you use “COM” objects such as Excel apps, workbooks and worksheets, it is very important for the code to “RELEASE” the com objects your code creates before you exit the program. In the current posted code, it is highly likely that there are lingering “Excel” resources still running. Therefore, to avoid leaking resources, it is important for your code to release the com objects it creates.
In my example below the code to release the resources is in the finally clause of the try/catch/finally statement.
private void button1_Click(object sender, EventArgs e) {
//SaveFileDialog saveFileD = new SaveFileDialog();
//string fileName = truckListBox.SelectedItem.ToString() + "__" + DateTime.Now.ToShortDateString();
string fileName = #"C:\Users\John\Desktop\Grr\TestExcelFile" + "__" + DateTime.Now.Year + "_" + DateTime.Now.Month;
//saveFileD.InitialDirectory = #"C:\Users\John\Desktop\Grr\";
//saveFileD.FileName = fileName;
//if (!Directory.Exists(#"C:/TML/"))
// Directory.CreateDirectory(#"C:/TML/");
//List<DataGridView> dataGridViews = getAllDataGridViews();
List<DataGridView> dataGridViews = getGrids();
Microsoft.Office.Interop.Excel.Application app = null;
Microsoft.Office.Interop.Excel.Workbook book = null;
Microsoft.Office.Interop.Excel.Worksheet sheet = null;
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
book = app.Workbooks.Add(System.Reflection.Missing.Value);
try {
foreach (var grid in dataGridViews) {
int count = book.Worksheets.Count;
//sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Sheets.Add(Type.Missing, book.Worksheets[count], Type.Missing, Type.Missing);
sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.Add();
//sheet.Name = grid.Name.ToString().Remove(0, 13);
sheet.Name = grid.Name.ToString();
int cMin = 1, rMin = 1;
int c = cMin, r = rMin;
// Set Headers
foreach (DataGridViewColumn column in grid.Columns) {
//Here appears the Error: System.Runtime.InteropServices.COMException: HRESULT: 0x800A03EC"
sheet.Cells[r, c] = column.HeaderText;
c++;
}
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].Font.Bold = true;
sheet.Range[sheet.Cells[r, cMin], sheet.Cells[r, c]].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Set Rows
foreach (DataGridViewRow row in grid.Rows) {
r++;
c = cMin;
// Set Cells
foreach (DataGridViewCell item in row.Cells) {
sheet.Cells[r, c++] = item.Value;
}
}
}
book.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing);
book.Close();
app.Quit();
}
catch (Exception ex) {
MessageBox.Show("Error writing to excel: " + ex.Message);
}
finally {
if (sheet != null)
Marshal.ReleaseComObject(sheet);
if (book != null)
Marshal.ReleaseComObject(book);
if (app != null)
Marshal.ReleaseComObject(app);
}
}
Hope this helps.
Simply Make a method and pass DataGridView
using Excel = Microsoft.Office.Interop.Excel;
public void ete(DataGridView dgv)//ExportToExcel
{
// Creating a Excel object.
Excel._Application excel = new Excel.Application();
Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
excel.Columns.ColumnWidth = 20;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
int cellRowIndex = 1;
int cellColumnIndex = 1;
//Loop through each row and read value from each column.
for (int i = -1; i < dgv.Rows.Count; i++)
{
for (int j = 0; j < dgv.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dgv.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dgv.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName.ToString());
MessageBox.Show("Export Successful");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}
Now Call Method
ete(datagridview1);

C# How to write each table in a Word file to its own Excel file

I'm trying to write code in C# WinForms that allows a user to select a directory tree, and extract all of the table data from a word document into an excel file. Presently, the code compiles and you can select your directories, etc, but once it begins to iterate through the loop for each table it crashes.
The program successfully opens the first word file and writes the first excel file (table_1_whatever.xlsx) and saves it in the destination folder. However, on the second table in the same file I get this error on this line of code:
worksheet.Cells[row, col] = objExcelApp.WorksheetFunction.Clean(table.Cell(row, col).Range.Text);
System.Runtime.InteropServices.COMException: 'The requested member of the collection does not exist.'
I can't seem to figure out why it doesn't exist. Each time it goes through the foreach loop it should be creating a new worksheet, but it doesn't appear to be working. Any insight, examples, or suggestions are welcome!
Code:
private void WordRunButton_Click(object sender, EventArgs e)
{
var excelApp = new excel.Application();
excel.Workbooks workbooks = excelApp.Workbooks;
var wordApp = new word.Application();
word.Documents documents = wordApp.Documents;
wordApp.Visible = false;
excelApp.Visible = false;
string[] fileDirectories = Directory.GetFiles(WordSourceBox.Text, "*.doc*",
SearchOption.AllDirectories);
foreach (var item in fileDirectories)
{
word._Document document = documents.Open(item);
int tableCount = 1;
foreach (word.Table table in document.Tables)
{
if (table.Cell(1, 1).ToString() != "Doc Level")
{
string wordFile = item;
appendName = Path.GetFileNameWithoutExtension(wordFile) + "_Table_" + tableCount + ".xlsx";
var workbook = excelApp.Workbooks.Add(1);
excel._Worksheet worksheet = (excel.Worksheet)workbook.Sheets[1];
for (int row = 1; row <= table.Rows.Count; row++)
{
for (int col = 1; col <= table.Columns.Count; col++)
{
var cell = table.Cell(row, col);
var range = cell.Range;
var text = range.Text;
var cleaned = excelApp.WorksheetFunction.Clean(text);
worksheet.Cells[row, col] = cleaned;
}
}
workbook.SaveAs(Path.Combine(WordOutputBox.Text, Path.GetFileName(appendName)), excel.XlFileFormat.xlWorkbookDefault);
workbook.Close();
Marshal.ReleaseComObject(workbook);
}
else
{
WordOutputStreamBox.AppendText(String.Format("Table {0} ignored\n", tableCount));
}
WordOutputStreamBox.AppendText(appendName + "\n");
tableCount++;
}
document.Close();
Marshal.ReleaseComObject(document);
WordOutputStreamBox.AppendText(item + "\n");
}
WordOutputStreamBox.AppendText("\nAll files parsed");
excelApp.Application.Quit();
workbooks.Close();
excelApp.Quit();
WordOutputStreamBox.AppendText("\nExcel files closed");
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelApp);
WordOutputStreamBox.AppendText("\nExcel files released");
wordApp.Application.Quit();
wordApp.Quit();
WordOutputStreamBox.AppendText("\nWord files have been quit");
Marshal.ReleaseComObject(documents);
Marshal.ReleaseComObject(wordApp);
WordOutputStreamBox.AppendText("\nWord files have been released\n");
}
Edit 1:(Sorry for posting in the wrong place the first time!)
Ok, so the problem has been isolated...
The code logic of the code was fine, and the table was in fact there. The issue is that the second table of these files has a set of split cells in it, so, when it reaches the cell that contains it, the program crashes.
As a temp fix, I have just set it to ignore the table if the header == whatever. Does anyone know of a solution that actually allows to extract this data though?

How to Set Values To Excel Sheet Cells

I am trying to set an Excel sheet specific cells starting at column A and second Excel sheet row. I wrote the following code:
if (!File.Exists(AppConfiguration.FilePath))
{
throw new FileNotFoundException("File Not Found. The requested template.xlsx was not found on the server");
}
Microsoft.Office.Interop.Excel.Application xlsx = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = null;
try
{
workbook = xlsx.Workbooks.Open(AppConfiguration.FilePath, ReadOnly: false, Editable: true);
Worksheet worksheet = workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range cells = worksheet.Cells["$A"];
List<Analytics> list = (List<Analytics>)data;
for (int i = 0; i < list.Count; i++)
{
((Microsoft.Office.Interop.Excel.Range)cells[i + 1, 0]).Value = list[i].ProductShare;
((Microsoft.Office.Interop.Excel.Range)cells[i + 1, 1]).Value = list[i].MarketPotential;
}
workbook.Save();
}
catch(Exception e)
{
throw new Exception("Error while processing file");
}
finally
{
workbook.Close(SaveChanges: true);
xlsx.Quit();
Marshal.ReleaseComObject(workbook);
}
However, I always get an Exception at
(Microsoft.Office.Interop.Excel.Range)cells[i + 1, 0]).Value = list[i].ProductShar
In Excel, indexes begin with 1, therefore cells[i + 1, 0]is invalid, use cells[i + 2, 1] instead.
for(int i = 0; i< list.Count; i++)
{
worksheet.Range[string.Format("A{0}", i + 2].Value = list[i].val;
}
Starting at A2 I begin to write the values within my list which is what I was seeking for! Thanks for all of you for your times and considerations!

How to add excel column to worksheet

Does any one know how to insert a new column to an already existing work sheet.
My current solution right now is to create a new excel file by copying all the columns from the existing excel then add the new col in the data table then exporting it to create a new excel. This method is somewhat tedious and just adding the new column to the already existing excel is the best way I see.
Here is my function for creating a new excel file
public static void ExportToExcel(DataTable tbl)
{
try
{
string dateNow = String.Format("{0:MM_dd_yyyy HH_mm_ss}", DateTime.Now);
string excelFilePath = "C:\\The_Excel_File\\Result_" + dateNow;
if (tbl == null || tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
var excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (var i = 0; i < tbl.Columns.Count; i++)
{
workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (var j = 0; j < tbl.Columns.Count; j++)
{
workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
}
}
// check file path
if (!string.IsNullOrEmpty(excelFilePath))
{
try
{
workSheet.SaveAs(excelFilePath);
excelApp.Quit();
//MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else
{ // no file path is given
excelApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
Open existing excel sheet and get columncount and Rowcount using sheet used Range as stated below and covert this values to rangeaddress to write existing excel sheet
Sheet.UsedRange.Columns.Count
Sheet.UsedRagne.Rows.Count

Categories

Resources