华工软院复试
C# XDocument库
-
调用
using System.Xml.Linq;
-
加载xml文件
XDocument doc = XDocument.Load("example.xml");
-
获取xml中的数据
IEnumerable<XElement> grades = doc.Descendants("grade"); //Descendants(XName)方法:按文档顺序返回此文档或元素的已筛选的子代元素集合。 集合中仅包括具有匹配XName的元素。 IEnumerable<XElement> grades = doc.Descendants("grade") .OrderByDescending(x => (double)x.Element("score")); //使用OrderByDescending()方法,重载排序方式,按元素内的score降序排序
-
对IEnumerable 的操作
foreach (XElement grade in grades)//获取枚举型中的每一个元素 { int id = (int)grade.Element("id"); string name = (string)grade.Element("name"); string course = (string)grade.Element("course"); double score = (double)grade.Element("score"); writer.WriteLine("{0},{1},{2},{3}", id, name, course, score); //写入txt文件 }
C# 文件操作 写文件
-
使用StreamWriter
StreamWriter writer = new StreamWriter("output.txt");
-
写入txt文件
writer.WriteLine("{0},{1},{2},{3}", id, name, course, score);
C# 数据库相关
-
数据库连接
using System.Data; using System.Data.SqlClient; //连接数据库所需库 SqlConnection connection = new SqlConnection(@"server=ServerName;database=SCUT_SE_19;Trusted_Connection=SSPI");//直接连接电脑数据库 //server=数据库服务器名称 connection.Open(); connection.Close();
-
使用SQL命令
SqlCommand command = new SqlCommand(@"insert into student values(" +"'"+studentId+"'," + "'" + studentName + "'," + "'" + gender + "');", connection); //构建sql语句 command.ExecuteNonQuery();//执行
19年xmlTotxt完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//需要使用IO和xml库
using System.IO;
using System.Xml.Linq;
namespace xmlTotxt
{
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("example.xml");
//加载xml文件
IEnumerable<XElement> grades = doc.Descendants("grade")
.OrderByDescending(x => (double)x.Element("score"));
//对读取出的doc以grade为单位按成绩排序,并给到枚举型的grades
using (StreamWriter writer = new StreamWriter("output.txt"))//文件输出流
{
foreach (XElement grade in grades)//获取枚举型中的每一个元素
{
int id = (int)grade.Element("id");
string name = (string)grade.Element("name");
string course = (string)grade.Element("course");
double score = (double)grade.Element("score");
writer.WriteLine("{0},{1},{2},{3}", id, name, course, score);
//写入txt文件
}
}
Console.WriteLine("Done.");
}
}
}
19年xmlToSql完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//调库
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;
namespace xmlTosql
{
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("example.xml");//读取xml文件
SqlConnection connection = new SqlConnection(@"server=DESKTOP-QDGMM2B;database=SCUT_SE_19;Trusted_Connection=SSPI");
connection.Open();
//与数据库建立连接
IEnumerable<XElement> students = doc.Descendants("student");
//冲xml文件中获取每一个单元
foreach(var student in students)
{
string studentId = student.Element("id").Value;
string studentName = student.Element("name").Value;
string gender = student.Element("gender").Value;
//获取数据
var command = new SqlCommand(@"insert into student values("
+"'"+studentId+"',"
+ "'" + studentName + "',"
+ "'" + gender + "');", connection);
//构建sql语句
command.ExecuteNonQuery();//执行
}
connection.Close();
}
}
}
18年txtToxml完整代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace SCUT_SE_18_prog
{
class Program
{
static void Main(string[] args)
{
string inputFile = "data.txt";
string outputFile = "output.xml";
List<Student> students = new List<Student>();
// 读取 txt 文件
using (StreamReader sr = new StreamReader(inputFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] fields = line.Split(',');
string id = fields[0];
string name = fields[1];
string courseName = fields[2];
string score = fields[3];
// 在学生列表中查找学生是否已存在
Student student = students.Find(s => s.Id == id);
if (student == null)
{
// 如果学生不存在,则新建一个学生
student = new Student(id, name);
students.Add(student);
}
// 添加该学生的成绩
student.AddScore(courseName, score);
}
}
// 生成 xml 文件
using (XmlWriter writer = XmlWriter.Create(outputFile))
{
writer.WriteStartElement("students");
foreach (Student student in students)
{
writer.WriteStartElement("student");
writer.WriteElementString("学号", student.Id);
writer.WriteElementString("姓名", student.Name);
foreach (var pair in student.Scores)
{
writer.WriteStartElement("课程");
writer.WriteAttributeString("课程名", pair.Key);
writer.WriteString(pair.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
Console.WriteLine("Done.");
Console.ReadLine();
}
}
class Student
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, string> Scores { get; set; }
public Student(string id, string name)
{
Id = id;
Name = name;
Scores = new Dictionary<string, string>();
}
public void AddScore(string courseName, string score)
{
Scores[courseName] = score;
}
}
}
txtTocsv
using System;
using System.IO;
namespace txtTocsv
{
class Program
{
static void Main(string[] args)
{
// 设置txt文件路径
string inputFilePath = @"D:\input.txt";
// 设置csv文件路径
string outputFilePath = @"D:\output.csv";
try
{
// 读取txt文件
string[] lines = File.ReadAllLines(inputFilePath);
// 打开csv文件,准备写入
using (StreamWriter writer = new StreamWriter(outputFilePath))
{
// 逐行读取txt文件并写入csv文件
foreach (string line in lines)
{
string[] fields = line.Split('\t');//以tab符进行划分,也可以以,划分
string csvLine = string.Join(",", fields);
writer.WriteLine(csvLine);
}
}
Console.WriteLine("成功将txt文件转换为csv文件!");
}
catch (Exception ex)
{
Console.WriteLine(@"发生错误:{ex.Message}");
}
Console.ReadKey();
}
}
}
csvTotxt
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string csvFilePath = @"D:\data.csv"; // csv文件路径
string txtFilePath = @"D:\data.txt"; // txt文件路径
StreamReader reader = new StreamReader(csvFilePath);
StreamWriter writer = new StreamWriter(txtFilePath);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');
foreach (string value in values)
{
writer.Write(value + "\t");
}
writer.WriteLine();
}
reader.Close();
writer.Close();
}
}
txtToexcel
using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace TxtToExcelConverter
{
class Program
{
static void Main(string[] args)
{
string txtFilePath = "path/to/your/txtfile.txt";
string excelFilePath = "path/to/your/excelfile.xlsx";
// Create an instance of the Excel application
Application excel = new Application();
// Create a new workbook
Workbook workbook = excel.Workbooks.Add();
// Get the first sheet in the workbook
Worksheet sheet = workbook.Sheets[1];
// Read the text file line by line
StreamReader reader = new StreamReader(txtFilePath);
string line;
int row = 1;
while ((line = reader.ReadLine()) != null)
{
// Split the line by tab delimiter
string[] columns = line.Split('\t');
// Write each column to the sheet
for (int col = 1; col <= columns.Length; col++)
{
sheet.Cells[row, col] = columns[col - 1];
}
row++;
}
// Save the workbook to the specified file path
workbook.SaveAs(excelFilePath);
// Close the workbook and the Excel application
workbook.Close();
excel.Quit();
Console.WriteLine("Txt file successfully converted to Excel.");
}
}
}
excelTotxt
using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace ExcelToTxt
{
class Program
{
static void Main(string[] args)
{
// 打开Excel文件
Application excelApp = new Application();
Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\excel\file.xlsx");
Worksheet worksheet = workbook.Worksheets[1];
// 创建输出文件
StreamWriter writer = new StreamWriter(@"C:\path\to\output\file.txt");
// 读取Excel中的内容并写入输出文件
Range range = worksheet.UsedRange;
for (int i = 1; i <= range.Rows.Count; i++)
{
string line = "";
for (int j = 1; j <= range.Columns.Count; j++)
{
line += Convert.ToString((range.Cells[i, j] as Range).Value2) + "\t";
}
writer.WriteLine(line.TrimEnd('\t'));
}
// 关闭Excel文件和输出文件
workbook.Close();
writer.Close();
Console.WriteLine("Excel file has been converted to text file.");
Console.ReadKey();
}
}
}
关于excel
需要注意的是,需要在项目中添加对Microsoft.Office.Interop.Excel的引用。在Visual Studio中,可以通过项目菜单 -> 添加引用 -> 选择COM选项卡 -> 搜索Microsoft Excel xx.0 Object Library来添加该引用。其中,xx.0表示安装在计算机上的Excel版本号。
注意,需要在项目中引用Microsoft.Office.Interop.Excel库。此外,以上代码只适用于Excel文件的第一个工作表,如果需要处理其他工作表或者指定行列范围,需要相应修改代码。
相关网址:
- 数据库编程 C# .net教程:https://blog.csdn.net/yongh701/article/details/50467129
- dddd:https://chat.forchange.cn/
- APIKEY:FCD4BB709E316C0591