My intention is opening 2 files (one .txt and one .csv), filter some text and finally write it into one column of single .csv file. Here is my code
OpenFileDialog fopen = new OpenFileDialog();
fopen.Multiselect = true;
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if (fopen.FileNames != null)
{
//try
//{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Add();
//Excel.Workbook wb = app.Workbooks.Open(fopen.FileName);
Excel.Worksheet sheet = wb.Sheets[1];
Excel.Range range = sheet.UsedRange;
int row = 1;
int col = 1;
foreach (string file in fopen.FileNames)
{
textBox1.Text = fopen.FileName;
string save = fopen.FileName;
string save1 = save.Split('.')[0];
string[] text = File.ReadAllLines(file);
for (int i = 0; i < lines; i++)
{
textBox2.AppendText(text[i] + "\n");
if (text[i].Contains("<LABEL-NAME>"))
{
if (text[i + 1].Contains("<MAP-LABEL-NAME>"))
{
string split = text[i].Split('<', '>')[2];
string split1 = text[i + 1].Split('<', '>')[2];
textBox3.AppendText(split + "\n");
textBox3.AppendText(split1 + "\n");
textBox4.Text = (split + ";" + split1);
string split2 = textBox4.Text;
range.Cells.set_Item(row, col, split2);
row++;
}
}
if (text[i].Contains("float32"))
{
string split = text[i].Split('f')[1];
textBox3.AppendText(split + "\n");
textBox4.Text = split;
range.Cells.set_Item(row, col, split);
row++;
}
textBox5.Text = row.ToString();
}
app.DisplayAlerts = false;
wb.SaveAs(save1 + ".csv", Excel.XlFileFormat.xlCSVWindows);
wb.Close(); //save as
app.Workbooks.Close();
app.Quit();
My problem is, the code has stop at
range.Cells.set_Item(row, col, split);
I try to pass the error but it has another problem is that just only the data filtered from the second file is written into the .csv file.
Can anyone tell me what am I doing wrong here?
Thank you.
Your fragment isn't complete but you appear to be opening Excel outside your foreach loop but closing it before the end, hence it doesn't exist if you open more than one file.
Excel.Application app = new Excel.Application();
.
.
foreach (string file in fopen.FileNames)
{
//file stuff
//} foreach loop should be closed here.
app.DisplayAlerts = false;
wb.SaveAs(save1 + ".csv", Excel.XlFileFormat.xlCSVWindows);
wb.Close(); //save as
app.Workbooks.Close();
app.Quit();
//} missing foreach closing bracket but implied
The rest of the fragment is missing but you need to close the foreach loop before closing Excel.
Related
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.
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);
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?
so currently my code below generates a string and adds it to a list for each image file in a directory, then after its does adding to the list, it opens an excel file, appends the list, and formats it. Currently my problem is that my excel line is selecting the entireColumn and pasting the list, how can I get it to recognize how many strings are in the list and only append that many to the excel sheet.
//Fill A2:B6 with an array of values .
oRng = oSheet.get_Range("C2");
oRng.EntireColumn.Value2 = checkInformation.ToArray();
Here is my whole project
class Program
{
[STAThread]
static void Main(string[] args)
{
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
Console.WriteLine("Initializing Check Parser Menu.....");
string dataPath = #"C:\Users\User\Desktop\Tesseract\Tesseract\tessdata";
string[] filePaths = Directory.GetFiles(#"C:\Users\User\Desktop\Tesseract\Tesseract\Check_Images", "*.png");
string checkData = "";
int checkCounter = 0;
List<string> checkInformation = new List<string>();
foreach (string filePath in filePaths)
{
checkCounter++;
Console.WriteLine("Initializing Check Parser... on Check: " + checkCounter);
using (TesseractEngine ocr = new TesseractEngine(dataPath, "eng", EngineMode.TesseractOnly))
{
using (Pix p = Pix.LoadFromFile(filePath))
{
using (Pix img = p.Scale(2, 3))
{
using (var page = ocr.Process(img))
{
string text = page.GetText();
if (text.Contains("Claim ID"))
{
int indexOfNone = text.IndexOf("NONE");
int indexOfClaimId = text.IndexOf("Claim ID");
int difference = indexOfClaimId - indexOfNone;
var dollarData = text.Substring(indexOfNone, difference);
int startingPoint = indexOfNone + (dollarData.Length - 6);
var dollarAmount = text.Substring(startingPoint, 6);
var claimIdData = text.Substring(indexOfClaimId, 14);
var claimInfoOutput = claimIdData + " Check Amount: " + dollarAmount;
Console.WriteLine(claimInfoOutput);
checkInformation.Add(claimInfoOutput);
}
else
{
Console.WriteLine("You will need to locate this check, there was an issue parsing " + "\n" + filePath);
Console.WriteLine("Press any Key to continue");
Console.ReadKey();
}
}
}
}
}
}
Console.WriteLine("Writing Data to Excel File... DONT TaCH");
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell. //Format A1:B1 as bold, vertical alignment = center.
oSheet.Cells[1, 1] = "Claim ID";
oSheet.Cells[1, 2] = "Check Amount";
oSheet.get_Range("A1", "B1").Font.Bold = true;
oSheet.get_Range("A1", "B1").VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
//Fill A2:B6 with an array of values .
oRng = oSheet.get_Range("C2");
oRng.Value2 = checkInformation.ToArray();
//oSheet.get_Range("A2", "B6").Value2 = checkInformation.ToArray();
//Fill A2 with a formula(=MID(C2,9,5)
oRng = oSheet.get_Range("A2", "A50");
oRng.Formula = "=MID(C2,9,5)";
//Fill B2 with a =RIGHT(C2,6)
oRng = oSheet.get_Range("B2", "B50");
oRng.Formula = "=RIGHT(C2,6)";
//AutoFit columns A:C.
oRng = oSheet.get_Range("A1", "C1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("C:\\Users\\User\\Desktop\\Tesseract\\Tesseract\\excel\\checkdata.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault,
Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close();
;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Okay I solved it guys sorry to bug you but heres what I did.
//Fill A2:B6 with an array of values .
string cellName;
int counter = 2;
foreach (var check in checkInformation)
{
cellName = "C" + counter.ToString();
oRng = oSheet.get_Range(cellName, cellName);
oRng.Value2 = check.ToString();
++counter;
}
and basically i just need to say for each item in my list this is the first cell name append the value.tostring
My ideal is : open some .csv files (5 or 6 or more) and add 2 new columns to all opened files and finally save it. Here is my code
OpenFileDialog fopen = new OpenFileDialog();
fopen.Multiselect = true;
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if (fopen.FileName != null)
{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(fopen.FileName);
Excel.Worksheet sheet = wb.Sheets[1];
Excel.Range range = sheet.UsedRange;
int column = range.Columns.Count;
int row = range.Rows.Count;
textBox1.Text = fopen.FileName;
//textBox2.Text = row.ToString();
//textBox3.Text = column.ToString();
range.Cells.set_Item(1, column + 1, "Mo_stMoC");
range.Cells.set_Item(1, column + 2, "Mo_stMoCCpl");
for (int i = 2; i <= row; i++)
{
range.Cells.set_Item(i, column + 1, "0");
range.Cells.set_Item(i, column + 2, "0");
}
wb.Save();
wb.Close();
app.Workbooks.Close();
app.Quit();
}
The problem is, when I open the files and it just adding 2 columns in the first .csv file.
I'm new to C#, so what am I doing wrong here?
you are opening multiple files, so loop through fopen.FileNames instead of just using fopen.FileName
foreach (String file in fopen.FileNames)
{
//do your thing
//edit
}
Additionally it is better to filter only csv files instead of all.
fopen.Filter = "CSV Files (*.csv)|*.csv";