C#Access数据库杂记

一、C#释放Access数据库文件

1
2
3
4
5
6
7
8
9
//连接数据库
string workspaceCON = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName;
ADODB.Connection cn = new ADODB.Connection();
cn.Open(workspaceCON, null, null, -1);
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.ActiveConnection = cn;
//释放数据库文件
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catalog.ActiveConnection);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catalog);

二、四舍六入五看前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
string x = corLPelevation.ToString();
//获取小数点的索引值
int index = x.IndexOf(".");
//小数点后第三位
string y3 = x.Substring(index + 3, 1);
int z3 = Convert.ToInt32(y3);
//小数点后第四位
string y4 = x.Substring(index + 4, 1);
int z4 = Convert.ToInt32(y4);
//判断第三位奇偶,奇=1,偶=0
int Conditions = z3 % 2;

double result = double.Parse(x);

//偶数
if (Conditions == 0)
{
//六进
if (z4 > 5)
{
result = Math.Round(result, 3);
}
//五舍
else if (z4 <= 5)
{
result = Math.Floor(result * 1000) / 1000;
}
}
//奇数
else if (Conditions == 1)
{
//四舍五进
result = Math.Round(result, 3);
}

三、C#实现txt查找替换并转换为excel工作表

string FileName = file.FileName;
//防止文本字符中有特殊字符。必须用Encoding.Default
StreamReader reader = new StreamReader(FileName, Encoding.Default);
String a = reader.ReadToEnd();
//将a.hhp文件中bb替换为cc。
a = a.Replace("a", "b");
a = a.Replace("a", "b");

//防止文本字符中有特殊字符。必须用Encoding.Default
StreamWriter readTxt = new StreamWriter(exePath + @"\转换.txt", false, Encoding.Default);
readTxt.Write(a);
readTxt.Flush();
readTxt.Close();
reader.Close();
//b.hhp重命名为a.hhp,并删除b.hhp
//File.Copy(@"b.hhp", @"a.hhp", true);
string path = exePath + @"\转换.txt";
StreamReader sr = new StreamReader(path);
string strLine = sr.ReadLine();
int rowNum = 1;
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Application.Workbooks.Add(true);
Workbook book = (Workbook)app.ActiveWorkbook;
Worksheet sheet = (Worksheet)book.ActiveSheet;
Range r = sheet.get_Range("A1", "C1");
//获取行数
object[,] objectData = new object[100, 100];
while (!string.IsNullOrEmpty(strLine))
{
    string[] tempArr;
    tempArr = strLine.Split(',');
    for (int k = 1; k <= tempArr.Length; k++)
    {
        objectData[rowNum - 1, k - 1] = tempArr[k - 1];
    }
    strLine = sr.ReadLine();
    rowNum++;
}
r = r.get_Resize(100, 100);
r.Value2 = objectData;
r.EntireColumn.AutoFit();
sr.Close();
//保存excel文件
book.SaveCopyAs(exePath + @"\转换.xlsx");
//关闭文件
book.Close(false, missing, missing);
//退出excel
app.Quit();
```);