콘솔창 ..
Excel.Range cellRow3 = worksheet.Cells[startRow, column]; //3행 2열
Excel.Range cellRow4 = worksheet.Cells[startRow + 1, column]; //4행 2열
Excel.Range cellRow5 = worksheet.Cells[startRow + 2, column ]; //5행 2열
startRow += 7;
이렇게 코드를 작성했는데 똑같은 코드만 떳었음
3행에 7행씩 더하면 안되고 //나는 7로해서 같은 행만 계속 나왔었음.
10행 첫행에 9행씩 더해줘야 12 ,21 ,30 행 ... 으로 돌면서 입력됨.
A = 3;
A
A+1
A+2
A = A + 9;
12행부터 13,14행 반복
----------------------------------------------------------------------
디버그 로그에
12
21
30
39
48
57
66
75
84
93
102
111
120
129
138
147
156
165
174
183
192
201
210
219
228
237
246
255
264
273
282
291
300
309
318
327
336
345
354
363
----------- 여기까지 출력되고 12 부터 다시 반복됨 363에서 9를 더했는데 빈칸이라 끝나는거 같음
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace exceltxt
{
internal static class Program
{
/// <summary>
/// 해당 애플리케이션의 주 진입점입니다.
/// </summary>
///
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
//파일 오픈 창 생성 및 설정
CommonOpenFileDialog opendlg = new CommonOpenFileDialog();
opendlg.IsFolderPicker = true;
//다이얼로그 타이틀설정
opendlg.Title = "폴더 선택";
opendlg.Multiselect = true;
//첫번째코드 여러개의 파일을 선택한경ㅇ우 모든파일의 경로를 배열로 저장
//string[] selectedFolder = null;
//pathFiles : 선택한 폴더 경로를 저장할 변수 pathFiles
if (opendlg.ShowDialog() == CommonFileDialogResult.Ok)
{
string selectedFolder = opendlg.FileName;
//opendlg.FileName : 선택한 파일의 경로를 반환
string[] excelFiles = Directory.GetFiles(selectedFolder, "*.xlsx");
//excelFiles : 선택한 폴더 내 모든 엑셀파일 경로
//// if 문 선택한 파일들의 경로(pathFiles)를 이용하여 추가 작업을 수행할 수 있음
// 선택한 폴더내 모든 엑셀파일에 대해 순차적으로 함수 호출
foreach (string filepath in excelFiles)
//excelFiles 반복하면서 루프 내부 코드 실행
//filepath : excelFiles 중 하나의 파일 엑셀경로
{
ProcessExcelFile(filepath);
//현재 엑셀 파일 경로가 인자로써 ProcessExcelFile 함수 호출
}
int a = 10;
}
else
{
return;
}
}
catch (Exception ex)
{
Console.WriteLine("Error :" + ex.Message + "ProcessWorksheet함수오류");
}
}
static void ProcessExcelFile(string filepath)
{
Excel.Application excelApp = new Excel.Application(); //오류
//excelApp으로 어플리케이션 조작
Excel.Workbook workbook = null;
try
{
workbook = excelApp.Workbooks.Open(filepath);
//파일명확인
Console.WriteLine(Path.GetFileName(filepath));
//파일명과 경로
//Console.WriteLine(Path.Combine("filepath1"));
foreach (Excel.Worksheet worksheet in workbook.Sheets)
//workbook.Sheets : 엑셀파일의 모든 시트
//각 시트 Excel.Worksheet 개체를 worksheet 변수에 할당
{
ProcessWorksheet(worksheet);
//호출
}
}
catch (Exception ex)
{
Console.WriteLine("Error :" + ex.Message);
}
finally
//메모리누수 방지 및 excel프로세스 정상종료, 무조건 실행
{
//workbook?.Close(false);
//null이 아닐경우 에만 메서드 호출 " ?. " 연산자 , false : 저장하지않고닫음
if (workbook != null)
{
Marshal.ReleaseComObject(workbook);
//COM개체 참조카운트 감소시켜 메모리 해제 . 메모리누수 방지(엑셀프로세스죽이기)
}
//문법이 다름 workbook?.Close(false);
}
}
static void ProcessWorksheet(Excel.Worksheet worksheet)
//현재 시트에 대한 작업
{
try
{
int startRow = 3 ; //시작행번호
int column = 2; //열 번호들
string txtFilePath = Path.ChangeExtension(worksheet.Parent.FullName + "_" + worksheet.Name, "txt");
using (StreamWriter writer = new StreamWriter(txtFilePath))
{
while (startRow <= worksheet.Cells.Rows.Count) //현재 행 번호가 시트의 전체 행수를 초과하지않는 동안 반복
{
Excel.Range cellRow3 = worksheet.Cells[startRow, column]; //3행 2열
Excel.Range cellRow4 = worksheet.Cells[startRow + 1, column]; //4행 2열
Excel.Range cellRow5 = worksheet.Cells[startRow + 2, column ]; //5행 2열
string valueRow3 = cellRow3.Value != null ? cellRow3.Value.ToString() : "";
string valueRow4 = cellRow4.Value != null ? cellRow4.Value.ToString() : "";
string valueRow5 = cellRow5.Value != null ? cellRow5.Value.ToString() : "";
if(valueRow3 == "")
//valueRow3이 비어있으면 리턴 문 사용하여 루프 조기종료
{
return;
}
writer.WriteLine($"{valueRow3}\t{valueRow4}\t{valueRow5}");
//텍스트파일에 tab으로 구분해서 한줄로 기록
//startRow += 7;
//마지막 값이 아니라면 줄바꿈 문자 추가하여 다음행으로 이동
//
if (IsEmptyRow(worksheet, startRow) && IsEmptyRow(worksheet, startRow + 1))
{
break; // Move to the next sheet
}
startRow += 9;
//시작행이 9 증가하고 다음행 그룹으로 이동
Trace.WriteLine($"{startRow}");
}
}
}
catch (Exception ex)
{
Trace.WriteLine("Error :" + ex.Message);
}
}
static bool IsEmptyRow(Excel.Worksheet worksheet, int row)
//둘다 비어있으면 루프에서 분리되어 현재시트 처리
{
Excel.Range cell = worksheet.Cells[row, 1];
return cell.Value == null || string.IsNullOrWhiteSpace(cell.Value.ToString());
}
}
}
startRow <= worksheet.Cells.Rows.Count 에 대한 GPT의 답변
여기서 worksheet.Cells.Rows.Count는 엑셀 시트의 전체 행 수를 나타냅니다. 조건식이 참인 경우, 현재 행 번호가 시트의 전체 행 수를 초과하지 않았으므로 아직 시트 내의 행을 처리할 수 있습니다. 따라서 이 조건식은 시트의 모든 행을 순회하는 데 사용됩니다.
즉, while (startRow <= worksheet.Cells.Rows.Count)는 "현재 행 번호가 시트의 전체 행 수를 초과하지 않는 동안 계속해서 반복하라"는 의미입니다. 이 조건식을 사용하여 엑셀 시트의 모든 행을 순회하면서 처리를 수행할 수 있습니다.
Trace.WriteLine($"{startRow}"); //디버그창에 현재 행 출력
카테고리 없음
C# winform 엑셀파일 특정값가져와서 txt파일로만들기(2)
728x90
728x90