乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > java如何直接从流中读取<em>excel</em>的文件内容?Stream-streamre

java如何直接从流中读取<em>excel</em>的文件内容?Stream-streamre

作者:乔山办公网日期:

返回目录:excel表格制作


可以将图片上传到指定目录并将路径记录在数据库中,要用的时候再从数据库中取路径根据路径找到图片。

也可以直接存在数据库中。SqlServer中用Image列来保存图片

两者各有千秋,从性能上考虑应用第一种,从安全上考虑应用第二种

以下为存在数据库中的例子:来源于百度
首先在SQL Server中建立一个图片存储的数库表,ImageData Column为图象二进制数据储存字段,ImageContentType Column为图象文件类型记录字段,ImageDescription Column为储蓄图象文件说明字段,ImageSize Column为储存图象文件长度字段,结构如下:7a64e59b9ee7ad94336
CREATE TABLE [dbo].[ImageStore] (
[ImageID] [int] IDENTITY (1, 1) NOT NULL ,
[ImageData] [image] NULL ,
[ImageContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[ImageDescription] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
[ImageSize] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
*/

//UpLoadImage.aspx程序内容如下:
<%@ Page Inherits="UploadImage.UploadImage" SRC="UpLoadImage.cs" Language="C#"%>
<HTML><title>上传图片</title>
<BODY bgcolor="#FFFFFF">
<FORM ENCTYPE="multipart/form-data" RUNAT="server" ID="Form1">
<TABLE RUNAT="server" WIDTH="700" ALIGN="left" ID="Table1" cellpadding="0" cellspacing="0" border="0">
<TR>
<TD>上传图片(选择你要上传的图片)</TD>
<TD>
<INPUT TYPE="file" ID="UP_FILE" RUNAT="server" STYLE="Width:320" ACCEPT="text/*" NAME="UP_FILE">
</TD>
</TR>
<TR>
<TD>
文件说明(添加上传图片说明,如:作者、出处)
</TD>
<TD>
<asp:TextBox RUNAT="server" WIDTH="239" ID="txtDescription" MAINTAINSTATE="false" />
</TD>
</TR>
<TR>
<TD>
<asp:Label RUNAT="server" ID="txtMessage" FORECOLOR="red" MAINTAINSTATE="false" />
</TD>
<TD>
<asp:Button RUNAT="server" WIDTH="239" ONCLICK="Button_Submit" TEXT="Upload Image" />
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
//-------------------------------------------------------------------
//UpLoadImage.cs程序内容如下:
using System;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace UploadImage
{
public class UploadImage : Page {
protected HtmlInputFile UP_FILE; //HtmlControl、WebControls控件对象
protected TextBox txtDescription;
protected Label txtMessage;
protected Int32 FileLength = 0; //记录文件长度变量
protected void Button_Submit(System.Object sender, System.EventArgs e) {
HttpPostedFile UpFile = UP_FILE.PostedFile; //HttpPostedFile对象,用于读取图象文件属性
FileLength = UpFile.ContentLength; //记录文件长度
try {
if (FileLength == 0) { //文件长度为零时
txtMessage.Text = "<b>请你选择你要上传的文件</b>";
} else {
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = UpFile.InputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);
//建立SQL Server链接
SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;");
String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = UpFile.ContentType; //记录文件类型
//把其它单表数据记录上传
CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = txtDescription.Text;
//记录文件长度,读取时使用
CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = UpFile.ContentLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功
}
} catch (Exception ex) {
txtMessage.Text = ex.Message.ToString();
}}}}
//----------------------------------------------------------------------
//好了,图片已经上传到数据库,现在还要干什么呢?当然是在数据库中读取及显示在Web页中啦,请看以下程序:
//ReadImage.aspx程序内容如下:
/-----------------------------------------------------------------------
<%@ Page Inherits="ReadImage.MainDisplay" SRC="ReadImage.cs"%>
//----------------------------------------------------------------------
//ReadImage.cs程序内容如下:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace ReadImage {
public class MainDisplay : System.Web.UI.Page {
public void Page_Load(System.Object sender, System.EventArgs e) {
int ImgID = Convert.ToInt32(Request.QueryString["ImgID"]); //ImgID为图片ID
//建立数据库链接
SqlConnection Con = new SqlConnection("Data Source=KING;Initial Catalog=testdb;User ID=sa;Pwd=;");
String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
Con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
SqlReader.Read();
Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
Response.End();
Con.Close();
//很简单吧^_^
}
}
}
//--------------------------------------------------------------------
//最后,我们当然要把它在Web页面显示出来啦
//ShowImage.hml
<html>
<body>
这个是从数据库读取出来的图象:<img src="ReadImage.aspx?ImgID=1">
<body>
</html>
//------------------------------------------------------------------

读取excel一般使用开源工具包来读取的。因为office文件是经过处理的,用流读到的都是乱码。
你可以自己从百度“java 去读excel”找些资料,一堆一堆的。而且都封装好了,用起来也方便。

我这也有代码。如果你找到的代码都不可用,我再发给你
1、方法一:采用OleDB读取EXCEL文件:
把EXCEL文件当做一个数据源来进行数据的读取操作,实例如下:

public DataSet ExcelToDS(string Path)
{
string
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path
+";"+"Extended Properties=Excel 8.0;";
OleDbConnection conn = new
OleDbConnection(strConn);
conn.Open();
string strExcel =
"";
OleDbDataAdapter myCommand = null;
DataSet ds =
null;
strExcel="select * from [sheet1$]";
myCommand = new
OleDbDataAdapter(strExcel, strConn);
ds = new
DataSet();
myCommand.Fill(ds,"table1");
return
ds;
}

对于EXCEL中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
OleDbConnection
conn = new OleDbConnection(strConn);
DataTable schemaTable =
objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);
string
tableName=schemaTable.Rows[0][2].ToString().Trim();

另外:也可进行写入EXCEL文件,实例如下:

public void DSToExcel(string Path,DataSet
oldds)
{
//先得到汇总EXCEL的DataSet 主要目的是获得EXCEL在DataSet中的结构
string strCon =
" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+path1+";Extended
Properties=Excel 8.0" ;
OleDbConnection myConn = new OleDbConnection(strCon)
;
string strCom="select * from [Sheet1$]";
myConn.Open ( ) ;

OleDbDataAdapter myCommand = new OleDbDataAdapter (
strCom, myConn ) ;
ystem.Data.OleDb.OleDbCommandBuilder builder=new
OleDbCommandBuilder(myCommand);

//QuotePrefix和QuoteSuffix主要是对builder生成7a686964616fe78988e69d83337InsertComment命令时使用。
builder.QuotePrefix="[";
//获取insert语句中保留字符(起始位置)
builder.QuoteSuffix="]";
//获取insert语句中保留字符(结束位置)
DataSet newds=new DataSet();
myCommand.Fill(newds
,"Table1") ;

for(int
i=0;i<oldds.Tables[0].Rows.Count;i++)
{
//在这里不能使用ImportRow方法将一行导入到news中,因为ImportRow将保留原来DataRow的所有设置(DataRowState状态不变)。

在使用ImportRow后newds内有值,但不能更新到Excel中因为所有导入行的DataRowState!=Added
DataRow
nrow=aDataSet.Tables["Table1"].NewRow();
for(int
j=0;j<newds.Tables[0].Columns.Count;j++)
{

nrow[j]=oldds.Tables[0].Rows[i][j];
}
newds.Tables["Table1"].Rows.Add(nrow);
}
myCommand.Update(newds,"Table1");
myConn.Close();
}
2、方法二:引用的com组件:Microsoft.Office.Interop.Excel.dll
读取EXCEL文件
首先是Excel.dll的获取,将Office安装目录下的Excel.exe文件Copy到DotNet的bin目录下,cmd到该目录下,运行
TlbImp EXCEL.EXE Excel.dll 得到Dll文件。 点击此处下载此文件:/Files/songliang/DLL文件.rar

再在项目中添加引用该dll文件.
//读取EXCEL的方法
(用范围区域读取数据)
private void OpenExcel(string
strFileName)

{
object missing =
System.Reflection.Missing.Value;

Application excel = new Application();//lauch excel
application
if (excel ==
null)

{

Response.Write("<script>alert('Can't access
excel')</script>");

}

else

{

excel.Visible = false; excel.UserControl =
true;
//
以只读的形式打开EXCEL文件

Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true,
missing, missing,
missing,

missing, missing, missing, true, missing, missing, missing, missing,
missing);

//取得第一个工作薄

Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);

//取得总记录行数
(包括标题列)

int rowsint = ws.UsedRange.Cells.Rows.Count;
//得到行数

//int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列数

//取得数据范围区域
(不包括标题列)

Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint);
//item

Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint);
//Customer

object[,] arryItem= (object[,])rng1.Value2; //get range's
value

object[,] arryCus =
(object[,])rng2.Value2;

//将新值赋给一个数组

string[,] arry = new string[rowsint-1,
2];
for
(int i = 1; i <= rowsint-1;
i++)

{

//Item_Code列

arry[i - 1, 0] =arryItem[i,
1].ToString();

//Customer_Name列

arry[i - 1, 1] = arryCus[i,
1].ToString();

}

Response.Write(arry[0, 0] + " / " + arry[0, 1] + "#" + arry[rowsint - 2, 0] + "
/ " + arry[rowsint - 2, 1]);

}
excel.Quit(); excel =
null;
Process[] procs =
Process.GetProcessesByName("excel");

foreach
(Process pro in procs)

{

pro.Kill();//没有更好的方法,只有杀掉进程

}

GC.Collect();
}
3、方法三:将EXCEL文件转化成CSV(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)。

先引用命名空间:
using System.Text;和using System.IO;

FileStream fs = new FileStream("d:\\Customer.csv", FileMode.Open,
FileAccess.Read,
FileShare.None);

StreamReader sr = new StreamReader(fs,
System.Text.Encoding.GetEncoding(936));

string str = "";

string s =
Console.ReadLine();

while (str !=
null)

{ str =
sr.ReadLine();

string[] xu = new
String[2];

xu =
str.Split(',');

string ser =
xu[0];

string dse =
xu[1];
if (ser ==
s)

{
Console.WriteLine(dse);break;

}
}
sr.Close();

另外也可以将数据库数据导入到一个txt文件,实例如下:

//txt文件名

string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" +
".txt";

OleDbConnection con = new
OleDbConnection(conStr);

con.Open();
string sql = "select
ITEM,REQD_DATE,QTY,PUR_FLG,PO_NUM from
TSD_PO014";

//OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014",
mycon);
//OleDbDataReader myreader
= mycom.ExecuteReader();
//也可以用Reader读取数据
DataSet ds = new
DataSet();
OleDbDataAdapter oda =
new OleDbDataAdapter(sql, con);

oda.Fill(ds, "PO014");
DataTable
dt = ds.Tables[0];

FileStream fs
= new FileStream(Server.MapPath("download/" + fn), FileMode.Create,
FileAccess.ReadWrite);

StreamWriter strmWriter = new StreamWriter(fs);
//存入到文本文件中

//把标题写入.txt文件中
//for (int i = 0; i
<dt.Columns.Count;i++)

//{
//
strmWriter.Write(dt.Columns[i].ColumnName + "
");

//}

foreach (DataRow dr in dt.Rows)

{
string
str0, str1, str2,
str3;

string str = "|";
//数据用"|"分隔开

str0 =
dr[0].ToString();

str1 =
dr[1].ToString();

str2 =
dr[2].ToString();

str3 =
dr[3].ToString();

str4 =
dr[4].ToString().Trim();

strmWriter.Write(str0);

strmWriter.Write(str);

strmWriter.Write(str1);

strmWriter.Write(str);

strmWriter.Write(str2);

strmWriter.Write(str);

strmWriter.Write(str3);

strmWriter.WriteLine(); //换行

}

strmWriter.Flush();

strmWriter.Close();
if (con.State
== ConnectionState.Open)

{

con.Close();
}

不行……

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网