关于C#中读写Microsoft Office Excel的说明

Application方式读写

添加COM程序集引用:Microsoft Excel 14.0 Object Library
添加using:Microsoft.Office.Interop.Excel

一、读取DataTable数据:

// 定义数据存储表
DataTable dataTable = new DataTable();
// Excel文件路径
string file = "C:/data.xls";
// 打开Excel应用程序
Application app = new Application();
// 设置Excel应用程序不可见
app.Visible = false;
// 读取Excel工作簿
Workbooks books = app.Workbooks;
_Workbook book = books.Add(file);
// 读取Excel工作表
Sheets sheets = book.Worksheets;
_Worksheet sheet = sheets.get_Item(1) as _Worksheet;
// 读取列名
for (int i = 0, length = sheet.Columns.Count; i < length; i++)
{
    dataTable.Columns.Add(sheet.Cells[1, i + 1].ToString());
}
// 读取行数据
for (int i = 0, iLength = sheet.Rows.Count; i < iLength; i++)
{
    object[] obj = new object[sheet.Columns.Count];
    for (int j = 0, jLength = sheet.Columns.Count; j < jLength; j++)
    {
        obj[j] = sheet.Cells[i + 2, j + 1];
    }
    dataTable.Rows.Add(obj);
}
// 不保存原始数据状态下关闭Excel应用程序
app.UserControl = false;
app.Quit();
return dataTable;

二、写入DataTable数据:

// 要写入的数据表
DataTable dataTable = new DataTable();
// Excel文件保存路径
string file = "C:/data.xls";
// 打开Excel应用程序
Application app = new Application();
// 设置Excel应用程序不可见
app.Visible = false;
// 读取Excel工作簿
Workbooks books = app.Workbooks;
_Workbook book = books.Add(XlWBATemplate.xlWBATWorksheet);
// 读取Excel工作表
Sheets sheets = book.Worksheets;
_Worksheet sheet = sheets.get_Item(1) as _Worksheet;
// 写入列名
for (int i = 0, length = dataTable.Columns.Count; i < length; i++)
{
    sheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName;
}
// 写入行数据
for (int i = 0, iLength = dataTable.Rows.Count; i < iLength; i++)
{
    for (int j = 0, jLength = dataTable.Columns.Count; j < jLength; j++)
    {
        sheet.Cells[i + 2, j + 1] = dataTable.Rows[i][j].ToString();
    }
}
// 保存Excel工作簿
book.SaveCopyAs(file);
book.Saved = true;
// 关闭Excel应用程序
app.UserControl = false;
app.Quit();

ADO.NET方式读写

一、获取Sheet名:

// 定义Sheet数据表名存储数组
string[] sheets = new string[] { };
// Excel文件路径
string file = "C:/data.xls";
// OleDb链接字符串
string connection = "Provider=Microsoft.Jet.OLEDB.4.0;";
connection += "Data Source=" + file + ";";
connection += "Extended Properties=Excel 8.0;";
// 打开OleDb链接
using (OleDbConnection con = new OleDbConnection(connection))
{
    con.Open();
    // 读取数据架构信息
    DataTable dataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    // 读取Sheet数据表名
    sheets = new string[dataTable.Rows.Count];
    for (int i = 0, length = dataTable.Rows.Count; i < length; i++)   
    {
        sheets[i] = dataTable.Rows[i]["TABLE_NAME"].ToString();
    }
    // 关闭OleDb链接
    con.Close();
}
return sheets;

二、读取DataTable数据:

// 定义数据存储表
DataTable dataTable = new DataTable();
// Excel文件路径
string file = "C:/data.xls";
// OleDb链接字符串
string connection = "Provider=Microsoft.Jet.OLEDB.4.0;";
connection += "Data Source=" + file + ";";
connection += "Extended Properties=Excel 8.0;";
// 打开OleDb链接
using (OleDbConnection con = new OleDbConnection(connection))
{
    con.Open();
    // 查询对应Sheet数据表的数据
    string sql = "select * from [sheet$]";
    // 读取表数据
    using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, con))
    {
        adapter.Fill(dataTable);
    }
    // 关闭OleDb链接
    con.Close();
}
return dataTable;

关于ASP.NET中服务端实现文件下载的说明

一、TransmitFile方式下载:

// Url编码下载文件名
string fileName = HttpUtility.UrlEncode("download.txt");
// 获取文件本地物理路径
string filePath = Server.MapPath("download.txt");
// 设置文件下载响应报文
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
// 输出下载文件数据
Response.TransmitFile(filePath);

二、WriteFile方式下载:

// Url编码下载文件名
string fileName = HttpUtility.UrlEncode("download.txt");
// 获取文件本地物理路径
string filePath = Server.MapPath("download.txt");
FileInfo fileInfo = new FileInfo(filePath);
// 设置文件下载响应报文
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = Encoding.Default;
// 输出下载文件数据
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();

三、FileStream方式下载:

// Url编码下载文件名
string fileName = HttpUtility.UrlEncode("download.txt");
// 获取文件本地物理路径
string filePath = Server.MapPath("download.txt");
// 读取文件数据
FileStream fileStream = new FileStream(filePath, FileMode.Open);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
fileStream.Close();
// 设置文件下载响应报文
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
// 输出下载文件数据
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();

四、FileStream分块下载:

// Url编码下载文件名
string fileName = HttpUtility.UrlEncode("download.txt");
// 获取文件本地物理路径
string filePath = Server.MapPath("download.txt");
FileInfo fileInfo = new FileInfo(filePath);
// 设置分块大小
int bufferLength = 1024;
byte[] buffer = new byte[bufferLength];
FileStream fileStream = File.OpenRead(filePath);
long downloadLength = fileStream.Length;
// 设置文件下载响应报文
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
// 分块输出下载文件数据
while (downloadLength > 0 && Response.IsClientConnected)
{
    int readLength = fileStream.Read(buffer, 0, bufferLength);
    Response.OutputStream.Write(buffer, 0, readLength);
    Response.Flush();
    downloadLength = downloadLength - readLength;
}
fileStream.Close();
Response.End();

五、断点续传下载:

// Url编码下载文件名
string fileName = HttpUtility.UrlEncode("download.txt");
// 获取文件本地物理路径
string filePath = Server.MapPath("download.txt");
FileStream fileStream = File.OpenRead(filePath);
long startPosition = 0;
long downloadLength = fileStream.Length;
Response.Clear();
// 读取请求下载文件区段
if (Request.Headers["Range"] != null)
{
    Response.StatusCode = 206;
    string[] split = Request.Headers["Range"].Replace("bytes=", "").Split('-');
    if (split.Length <= 0 || !long.TryParse(split[0], out startPosition))
    {
        startPosition = 0;
    }
    // 设置当前文件区段响应报文
    Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startPosition, fileStream.Length - 1, fileStream.Length));
    downloadLength -= startPosition;
}
// 设置文件下载响应报文
Response.AddHeader("Content-Length", downloadLength.ToString());
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
// 定位区段位置读取文件区段数据
byte[] buffer = new byte[downloadLength];
fileStream.Position = startPosition;
fileStream.Read(buffer, 0, buffer.Length));
fileStream.Close();
// 输出下载文件区段数据
Response.BinaryWrite(buffer);
Response.End();

关于C#中以管理员身份运行程序的说明

在使用C#编写程序时,如果程序是需要在Windows 7以上的操作系统上运行,有时会需要以管理员身份才能正常启动,否则会因为权限不足而出错,那如何让我们的程序自动提示以管理员身份运行呢?
我们可以按照以下方法进行操作。

一:在Visual Studio中–解决方案资源管理器–右键项目名称–属性,找到“安全性”选项:
csharp-admin-run-1

二:勾选“启用ClickOnce安全设置”并保存:
csharp-admin-run-2

三:这时,在项目下面会多出一个“app.manifest”的文件:
csharp-admin-run-3
选中它打开,并找到代码段:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

将其改为:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

csharp-admin-run-4
将上图红框部分修改为:
csharp-admin-run-5

四:改正保存后,不要急于重新编译生成,再次打开“属性–安全性”界面,将“启用ClickOnce安全设置”前面的勾去掉并保存后再编译运行:
csharp-admin-run-6

五:最后,保存修改,重新编译运行程序。

完成以上操作后再打开程序时,会提示“用户账户控制”来获取管理员权限运行,点击“是”则获取了管理员权限。