0의 자율 학습 C#03 - 파일 스트림은 데이터를 txt/excel 형식으로 저장합니다.
데이터를 txt 및 Excel 형식으로 저장하기 위한 DataTable, 로그 Log, 파일 스트림 FileStream 및 StreamWriter 클래스를 주로 소개합니다.
1. TestDataTable 클래스 생성
CreateTable() 메서드는 데이터 테이블을 생성하고, SaveTableToExcel(string fileName) 메서드는 데이터 테이블을 fileName, CreateDirectory(string fileName)이라는 Excel 형식 파일로 저장합니다. ) 파일이 존재하는지 확인하는 방법입니다. 파일이 존재하지 않으면 자동으로 생성됩니다.
class TestDataTable: DataTable { public void CreateTable() { this.Columns.Add("Time(s)", System.Type.GetType("System.String")); this.Columns.Add("Ch", System.Type.GetType("System.String")); this.Columns.Add("BER", System.Type.GetType("System.String")); const int length1 = 4; const int length2 = 10; int[][] data = new int[length1][]; //第一条数据 data[0] = new int[length2] { 13, 25, 21, 33, 28, 39, 43, 36, 42, 36 }; //第二条数据 data[1] = new int[length2] { 20, 13, 10, 5, 15, 7, 10, 14, 19, 20 }; //第三条数据 data[2] = new int[length2] { 78, 92, 65, 83, 90, 59, 63, 72, 88, 98 }; //第四条数据 data[3] = new int[length2] { 45, 49, 39, 47, 52, 76, 67, 51, 57, 67 }; for (int i = 0; i < length2; i++) { for (int j = 0; j < length1; j++) { DataRow dr = this.NewRow(); dr[0] = i + 1; dr[1] = j; dr[2] = data[j][i]; this.Rows.Add(dr); } } } public void SaveTableToExcel(string fileName) { CreateDirectory(fileName); StringBuilder title = new StringBuilder(); FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate); StreamWriter writer = new StreamWriter(new BufferedStream(fileStream), System.Text.Encoding.Default); for (int i = 0; i < this.Columns.Count; i++) { title.Append(this.Columns[i].ColumnName + "\t"); //栏位:自动跳到下一单元格 } title.Append("\n"); writer.Write(title); foreach (DataRow row in this.Rows) { StringBuilder content = new StringBuilder(); for (int i = 0; i < this.Columns.Count; i++) { content.Append(row[i] + "\t");//内容:自动跳到下一单元格 } content.Append("\n"); writer.Write(content); } writer.Close(); fileStream.Close(); } public void CreateDirectory(string fileName) { DirectoryInfo directoryInfo = Directory.GetParent(fileName); if (!directoryInfo.Exists) { directoryInfo.Create(); } } }
2. 로그 클래스 생성
파일 이름 FileName을 클래스의 속성으로 정의하고 생성자에서 할당합니다. SaveLogToTxt(string info) 메서드는 데이터 정보를 fileName이라는 txt 파일에 저장합니다. 동일한 CreateDirectory() 메서드로 파일이 존재하는지 확인합니다
class Log { private string fileName; public string FileName { set { this.fileName = value; } get { return this.fileName; } } public Log(string fileName) { this.fileName = fileName; CreateDirectory(); } public void SaveLogToTxt(string info) { StreamWriter writer = null; FileStream fileStream = null; try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(this.fileName); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine(info); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } } public void CreateDirectory() { DirectoryInfo directoryInfo = Directory.GetParent(this.fileName); if (!directoryInfo.Exists) { directoryInfo.Create(); } } }
3. 클래스 메서드를 호출하여 데이터를 저장합니다
클래스를 인스턴스화하고 데이터 테이블을 생성한 후 txt 형식으로 테이블을 저장합니다. 시간 이름이 포함된 Excel 형식입니다.
TestDataTable dt = new TestDataTable(); dt.CreateTable(); dt.Rows.Clear(); //清除数据table里所有行DateTime startTime = DateTime.Now; Log log = new Log(@"Log\" + startTime.ToString("yyyyMMddHHmmss") + ".txt");//以时间为文件命名,存在exe所在文件夹下的Log文件夹里for (int i = 0; i < 4; i++) { DataRow dr = dt.NewRow(); dr[0] = (int)second; dr[1] = i; dr[2] = BERByChannel[i].ToString("E2"); dt.Rows.Add(dr);//添加新行到数据table string info = string.Format("{0}: Time(s): {1}, Ch: {2}, BER: {3}", DateTime.Now, dr[0], dr[1], dr[2]); log.SaveLogToTxt(info);//存为txt格式 }//存为excel格式string fileName = @"TestRecord\" + startTime.ToString("yyyyMMddHHmmss") + ".xls"; dt.SaveTableToExcel(fileName);//以时间为文件命名,存在exe所在文件夹下的TestRecord文件夹里
위 내용은 0-파일 스트림에서 데이터를 txt/excel 형식으로 저장하는 C#03 자습 내용입니다. 더 많은 관련 내용은 PHP 중국어 웹사이트(www.php)를 참고하세요. .cn)!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











C#을 사용한 Active Directory 가이드. 여기에서는 소개와 구문 및 예제와 함께 C#에서 Active Directory가 작동하는 방식에 대해 설명합니다.

C#의 액세스 수정자에 대한 안내입니다. 예제 및 출력과 함께 C#의 액세스 한정자의 소개 유형에 대해 논의했습니다.

C#의 난수 생성기 가이드입니다. 여기서는 난수 생성기의 작동 방식, 의사 난수 및 보안 숫자의 개념에 대해 설명합니다.

C# 데이터 그리드 뷰 가이드. 여기서는 SQL 데이터베이스 또는 Excel 파일에서 데이터 그리드 보기를 로드하고 내보내는 방법에 대한 예를 설명합니다.

C# StringReader에 대한 안내입니다. 여기에서는 C# StringReader에 대한 간략한 개요와 다양한 예제 및 코드와 함께 작동하는 방법에 대해 설명합니다.

C# StringWriter 가이드. 여기에서는 C# StringWriter 클래스에 대한 간략한 개요와 다양한 예제 및 코드와 함께 작동하는 방법에 대해 설명합니다.
